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?


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

align-self: center;

See documentation here: align-self


The key attribute is align-self: center:

.container {
  display: flex;
  flex-direction: column;
}

img {
  max-width: 100%;
}

img.align-self {
  align-self: center;
}
<div class="container">
    <p>Without align-self:</p>
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />
    <p>With align-self:</p>
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />
</div>

I faced the same issue with a Foundation menu. align-self: center; didn't work for me.

My solution was to wrap the image with a <div style="display: inline-table;">...</div>