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

Time:11-30

#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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

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

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Here the another way without using flex: I will recommend that display:flex; will be the good and easy one.

#myDiv {
    display: inline-block;
    border: 1px solid red;
    width: 200px;
    position: relative;
    padding-left: 22px;
}

#myImg {
    position: absolute;
    left: 0;
    height: 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>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related