DasBeasto
DasBeasto

Reputation: 2282

How to prevent flexbox stretching my image horizontally?

I saw this question about flexbox stretching images vertically, and applying align-self: center fixes it: Why does flexbox stretch my image?

However, I have an issues with my images stretched horizontally: https://jsfiddle.net/qnnpxskk/

HTML:

<div class="wrapper">
  <div class="inner">
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
  </div>
</div>

CSS:

.wrapper{
  width: 600px;
  height: 900px;
  background: white;
}
.inner{
  display: flex;
  flex-direction: column;
}
.row{
  max-height: 100px;
  margin: 20px;
  display: flex;
  flex-direction: row;
  background: red;
}
.row img{
  max-height: 100%;
}

Everything I try I can't seem to get the image to not be stretched. I want the image to be 100% height of the parent and the width to maintain aspect ratio of the original.

Upvotes: 1

Views: 2379

Answers (1)

LKG
LKG

Reputation: 4192

Update css part

.row img{
  max-height: 100%;
  object-fit:contain; /* Add this You can change it as your need */
}
.inner{
  display: flex;
  flex-flow:column nowrap;
  justify-content:flex-start;
}
.wrapper{
  width: 100%; /*Add this*/
  height: 900px;
  background: white;
}

update fiddle

Update fiddle

.wrapper{
  width: 100%;
  height: 900px;
  background: white;
}
.inner{
  display: flex;
  flex-flow:column nowrap;
  justify-content:flex-start;
}
.row{
  max-height: 100px;
  margin: 20px;
  display: flex;
  flex-direction: row;
  background: red;
}
.row img{
  max-height: 100%;
  object-fit:contain;
}
<div class="wrapper">
  <div class="inner">
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
    <div class="row">
      <img src="https://www.wired.com/wp-content/uploads/2015/11/google-tensor-flow-logo-F.jpg">
    </div>
  </div>
</div>

About object-fit https://css-tricks.com/almanac/properties/o/object-fit/

Upvotes: 3

Related Questions