0

I'm using jquery to calculate the aspect ratio of images and setting that as the flex-grow value so that all images within the flexbox appear the same height while filling the width of the container.

This works great in Firefox, but has different behaviour in Chrome.

In Firefox, all images are the same height and maintain their aspect ratios.

In Chrome, all images appear to have the same width as in Firefox, but they are vertically stretched to the height of the tallest item, 500px.

How can I fix how this looks in Chrome?

$('div.pack').css({
    "display": "flex"
  })
  .children().each(function() {
    var aspect = this.naturalWidth / this.naturalHeight;
    $(this).wrap('<div style="display:flex; flex: 0% ' + aspect + ' 1;" />')
  });
img {
  width: 100%;
  height: auto;
}

div.pack > div:not(:last-child) {
  margin-right: 2%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='pack'>
  <img src="http://via.placeholder.com/400x150"/>
  <img src="http://via.placeholder.com/150x500"/>
  <img src="http://via.placeholder.com/300x300"/>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165
43Tesseracts
  • 4,617
  • 8
  • 48
  • 94

1 Answers1

1

You will need to add align-items: flex-start to the div wrapper's CSS, or else Chrome will stretch the img as the default value for align-items is just that, stretch.

I also changed the order of the shorthand flex properties to their correct position

Also note, using percent for margin and padding on flex items might render different based on the fact that the specs. allows it, and it is recommended not to.

Stack snippet

$('div.pack').css({
    "display": "flex"
  })
  .children().each(function() {
    var aspect = this.naturalWidth / this.naturalHeight;
    $(this).wrap('<div style="display: flex; align-items: flex-start; flex: ' + aspect + ' 1 0%;" />')
  });
img {
  width: 100%;
  height: auto;
}

div.pack > div:not(:last-child) {
  margin-right: 2%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='pack'>
  <img src="http://via.placeholder.com/400x150"/>
  <img src="http://via.placeholder.com/150x500"/>
  <img src="http://via.placeholder.com/300x300"/>
</div>

Another option would be to simply remove display: flex on the div wrapper's.

Stack snippet

$('div.pack').css({
    "display": "flex"
  })
  .children().each(function() {
    var aspect = this.naturalWidth / this.naturalHeight;
    $(this).wrap('<div style="flex: ' + aspect + ' 1 0%;" />')
  });
img {
  width: 100%;
  height: auto;
}

div.pack > div:not(:last-child) {
  margin-right: 2%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='pack'>
  <img src="http://via.placeholder.com/400x150"/>
  <img src="http://via.placeholder.com/150x500"/>
  <img src="http://via.placeholder.com/300x300"/>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165