Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fit an image inside a container with non-fixed height?

#myDiv {
  display: inline-block;
  border:1px solid red;
  width:200px;
}
#myImg {
  max-height:100%;
  max-width:100%;
}
#anotherDiv {
  display:inline-block;
  border:1px solid blue;
  height:100px;
  width:50px;
}
<div id="myDiv">
<img src='https://i.imgur.com/rw9ypWD.png' id="myImg">
<div id="anotherDiv">
</div>
</div>

I want to fit the image height to its container div.

Using height:100%; works only when the container have a fixed height.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Simply add display:flex to container to get the stretch alignment by default:

#myDiv {
  display: inline-flex;
  border:1px solid red;
  width:200px;
}
#anotherDiv {
  display:inline-block;
  border:1px solid blue;
  height:100px;
  width:50px;
}
<div id="myDiv">
<img src='https://i.imgur.com/rw9ypWD.png' id="myImg">
<div id="anotherDiv">
</div>
</div>

A different result with display:grid:

#myDiv {
  display: inline-grid; 
  grid-auto-flow:column; /* column flow */
  justify-content: flex-start; /* align everything to left */
  border:1px solid red;
  width:200px;
}
#myImg {
  height:100%; /* image 100% height of the div */
}
#anotherDiv {
  display:inline-block;
  border:1px solid blue;
  height:100px;
  width:50px;
}
<div id="myDiv">
<img src='https://i.imgur.com/rw9ypWD.png' id="myImg">
<div id="anotherDiv">
</div>
</div>

<div id="myDiv">
<img src='https://i.imgur.com/rw9ypWD.png' id="myImg">
<div id="anotherDiv" style="height:50px">
</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading