Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep aspect ratio of vertical aligned image in flex box

img{
  max-height: 100%;
  max-width: 100%;
  width: auto;
  height: auto;
}

The full code can be seen here: http://jsfiddle.net/ZSSVt/

I want the image to "auto-fit" inside its div container, like here: http://jsfiddle.net/y4Y3S/ (but vertically aligned).

Right now the kitten gets squished when the image is resized. How to fix that?

like image 493
thelolcat Avatar asked Oct 21 '22 12:10

thelolcat


1 Answers

updated jsFiddle

Try wrapping the image in another div. <img> elements behave differently than <div> elements when width and height are applied.

For example width: 100% applied to <img> means that the image element will have the same width as the source picture. If you apply width: 100% to <div>, it would have the same width as the first parent with defined width.

Thus, your desired html will be:

<div class='box'>
    <div class='wrapper'>
        <img src="http://placekitten.com/g/200/300" />
    </div>
</div>    

With corresponding css for wrapper div:

div.wrapper {max-height:100%;}
like image 68
Lukas Vrabel Avatar answered Oct 23 '22 03:10

Lukas Vrabel