Using the CSS flex box model, how can I force an image to maintain its aspect ratio?
JS Fiddle: http://jsfiddle.net/xLc2Le0k/2/
Notice that the images stretch or shrink in order to fill the width of the container. That's fine, but can we also have it stretch or shrink the height to maintain the image proportions?
HTML
<div class="slider">
<img src="http://www.placebacon.net/400/300" alt="Bacn">
<img src="http://www.placebacon.net/400/300" alt="Bacn">
<img src="http://www.placebacon.net/400/300" alt="Bacn">
<img src="http://www.placebacon.net/400/300" alt="Bacn">
</div>
CSS
.slider {
display: flex;
}
.slider img {
margin: 0 5px;
}
To keep images from stretching in either axis inside a flex parent I have found a couple of solutions.
You can try using object-fit on the image which, e.g.
object-fit: contain;
Or you can add flex-specfic rules which may work better in some cases.
align-self: center;
flex: 0 0 auto;