14

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

Community
  • 1
  • 1
BonsaiOak
  • 27,741
  • 7
  • 30
  • 54
  • Do you need to use display:flex? If you use display:inline-block, you get what you're looking for. – Cruiser Oct 28 '15 at 16:59
  • @Cruiser I'd rather use flexbox but you're right, `display: inline-block` does the trick just fine. (As long as I remember to comment out the whitespace between the divs) – BonsaiOak Oct 28 '15 at 17:07
  • Where have you read that this is a Chrome bug? I couldn't find that statement on the linked page. – ygoe Nov 28 '18 at 22:26

3 Answers3

19

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%;
}
Gerrit Bertier
  • 4,101
  • 2
  • 20
  • 36
18

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

Community
  • 1
  • 1
Chelsea
  • 431
  • 4
  • 5
  • Brilliant! I was banging my head against the table for some days trying to make it work! – Alexandr Zarubkin Aug 22 '18 at 13:28
  • If you need this to work on Internet Explorer, this solution doesn’t work, unfortunately… – gnclmorais Apr 17 '19 at 07:24
  • This solved an issue only on chrome for me where aspect ratio was fine on load but using js to add/remove `display: none` to show hide image wouldn't preserve aspect ratio – Kerkness Jul 23 '20 at 12:18
-2

You can solve this by adding the height property to your img rule and giving it a value of auto:

img{
    height:auto;
    width:50%;
}
Shaggy
  • 6,696
  • 2
  • 25
  • 45