Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome doesn't respect image aspect ratio in flexbox

Flexboxes make it easy to make layouts that grow and shrink intelligently based on available space. I was using this feature to draw two images that each take up half of the width of the screen. In Firefox, the images render as expected and maintain their aspect ratio but in Chrome the images are horizontally squashed to 50% each and left at their full height vertically.

Here's a demo of what I'm talking about:

.flexbox {
  width: 100%;
  display: flex;
}
img {
  width: 50%;
}
<div class="flexbox">
  <img src="http://res1.windows.microsoft.com/resbox/en/windows/main/2b03b0c4-85f7-4c28-9c60-1c7af2a62fa8_5.jpg" />
  <img src="http://res1.windows.microsoft.com/resbox/en/windows/main/b89eff70-398d-4b1b-8806-02458a185c5a_5.jpg" />
</div>

I've read in an answer to a similar question that this is a Chrome bug. How can I cleanly work around it?

Thanks

like image 273
BonsaiOak Avatar asked Oct 28 '15 16:10

BonsaiOak


People also ask

How do you preserve aspect ratio when scaling images?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.

How do I fix the aspect ratio in CSS?

The ratio 9/16 is ease to change, no need to predefined 100:56.25 or 100:75 . If you want to ensure height first, you should switch width and height, e.g. height:100vh;width: calc(100vh * 9 / 16) for 9:16 portrait.

How do I change the aspect ratio of an image in CSS?

Sometimes, it is required to fit an image into a certain given dimension. We can resize the image by specifying the width and height of an image. A common solution is to use the max-width: 100%; and height: auto; so that large images do not exceed the width of their container.

How do I change the aspect ratio of an image in HTML?

If your image doesn't fit the layout, you can resize it in the HTML. One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.


2 Answers

The items in a flexbox will stretch their size by default. Seeing you want them to not stretch on the cross-axis (vertical), you can use the align-items on the container, to change the default behaviour.

Fiddle: http://jsfiddle.net/g1vLff23/

CSS

.flexbox {
  width: 100%;
  display: flex;
  align-items: flex-start;
}
img {
  width: 50%;
}
like image 179
Gerrit Bertier Avatar answered Oct 20 '22 20:10

Gerrit Bertier


Apply object-fit: scale-down; to the images. Yes, adding height: auto; does not do the trick, unfortunately. Similar issue solved here: max-width of img inside flexbox doesn't preserve aspect ratio

like image 18
Chelsea Avatar answered Oct 20 '22 20:10

Chelsea