Why is height:auto not working for this image?

Viewed 1219

I have a flexbox container with two flex items in it. One is an image and the other a paragraph. I've been trying to resize the image proportionally by giving width:some-percentage and height:auto but it's not working. Please help me solve this.

.item{
  display:flex;
}
img{
  width: 25%; /* not working */
  height: auto;
}
<div class="item">
  <img
  src=
  "https://png.pngtree.com/element_origin_min_pic/16/10/16/105802ebe43fe0f.jpg"/>
  <p>some paragraph</p>
</div>

JSFiddle link - https://jsfiddle.net/dizzyramen/xfot3Lwv/2/

3 Answers

A default setting on a flex container is align-items: flex-start.

In a row-direction container, this makes flex items, not having a defined height (e.g. height: auto), extend the full height of the container (full explanation).

In this particular case, however, the image is stretching to its fullest, and expanding the size of the container along with it.

The solution is to set a height limit on the container or override the default with align-items: flex-start on the container or align-self: flex-start on the item.

jsFiddle demo

.item {
  display: flex;
}

img {
  width: 25%;
  align-self: start; /* new */
}
<div class="item">
  <img src="https://png.pngtree.com/element_origin_min_pic/16/10/16/105802ebe43fe0f.jpg" />
  <p>some paragraph</p>
</div>

here is another option:

  • wrap your img in a div <div class="image-wrapper"> and set manage the width in this node.
  • asign width: 100%; height: auto; to the img so it adjust proportionally to its parent.
  • Here you have it in a snippet. Hope it helps.

<div class="item">
    <div class="image-wrapper">
        <img
            src=
  "https://png.pngtree.com/element_origin_min_pic/16/10/16/105802ebe43fe0f.jpg"/>
    </div>
    <p>some paragraph</p>
</div>

<style>
.item{
  display:flex;
}
.image-wrapper {
  width: 25%; /* means 25% of .item */
}
img{
  width: 100%; /* means 100% of its parent .image-wrapper */
  height: auto;
}
</style>

It happens because, per default the tag <img>is inline. You need to change it to block or flex

Related