Search code examples
htmlcssflexbox

Why does flexbox stretch my image rather than retaining aspect ratio?


Flexbox has this behaviour where it stretches images to their natural height. In other words, if I have a flexbox container with a child image, and I resize the width of that image, the height doesn't resize at all and the image gets stretched.

div {
  display: flex; 
  flex-wrap: wrap;
}

img {
  width: 50%
}
<div>
    <img src="https://i.imgur.com/KAthy7g.jpg" >
    <h1>Heading</h1>
    <p>Paragraph</p>
</div>

What causes this?


Solution

  • It is stretching because align-self default value is stretch. Set align-self to center.

    align-self: center;
    

    See documentation here: align-self