pruoccojr
pruoccojr

Reputation: 482

display:flex & image sizing/centering

I am using display: flex; to center an image and max-width / max-height to size it. There are several of these images - some wide, some tall, some square - and I want to be sure they are all a decent enough size to view them.

I assumed that if, for example, the image hits the maximum width and not the height, it should stay in proportion to the width.

Here is the issue I'm having. In chrome, it looks perfect for all images. In Firefox and Edge, they are skewed out of proportion.

Compaison between chrome and firefox/edge

.image_block {
  padding: 20px;
  height: 140px;
  background: #eee;
  display: flex;
}
.image_block img {
  margin: auto;
  max-width: 170px;
  max-height: 90px;
}
<div class="image_block">
  <img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" />
</div>

I don't care which result I end up with (I can work with either) but I would like all three of them consistent. What can I do to accomplish this?

Upvotes: 1

Views: 1389

Answers (1)

kukkuz
kukkuz

Reputation: 42370

It seems flexbox do not scale down images (that have an intrinsic aspect ratio) correctly in browsers at the moment, at least! (For more info, you can look at this discussion)

So I have two solutions for this:

  1. Set flex-basis for the img

.image_block {
  padding: 20px;
  height: 140px;
  background: #eee;
  display: flex;
}
.image_block img {
  margin: auto;
  max-width: 170px;
  max-height: 90px;
  flex-basis: 170px;
}
<div class="image_block">
  <img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" />
</div>

  1. Wrap the img with a div tag.

.image_block {
  padding: 20px;
  height: 140px;
  background: #eee;
  display: flex;
}
.image_block div {
  margin: auto;
}
.image_block div img {
  max-width: 170px;
  max-height: 90px;
}
<div class="image_block">
  <div><img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" /></div>
</div>

Also I would suggest you use flexbox techniques instead of using margin: auto:

.image_block {
  padding: 20px;
  height: 140px;
  background: #eee;
  display: flex;
  justify-content: center;
  align-items: center;
}
.image_block img {
  max-width: 170px;
  max-height: 90px;
  flex-basis: 170px;
}
<div class="image_block">
  <img src="http://www.paulruocco.com/jobjacket/assets/uploads/company_uploads/image_070816132332577fe19495484.png" />
</div>

Let me know your feedback on this. Thanks!

Upvotes: 2

Related Questions