Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

You might want to try the very new and simple CSS3 feature:

img { 
  object-fit: contain;
}

It preserves the picture ratio (as when you use the background-picture trick), and in my case worked nicely for the same issue.

Be careful though, it is not supported by IE (see support details here).

If you wish to specify a specific aspect ratio, you can combine it with the aspect-ratio property

img { 
  object-fit: contain;
  aspect-ratio:2/1;
}

I came here looking for an answer to my distorted images. Not totally sure about what the op is looking for above, but I found that adding in align-items: center would solve it for me. Reading the docs, it makes sense to override this if you are flexing images directly, since align-items: stretch is the default. Another solution is to wrap your images with a div first.

.myFlexedImage {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

img {max-width:100%;} is one way of doing this. Just add it to your CSS code.

http://jsfiddle.net/89dtxt6s/

Tags:

Html

Css

Flexbox