1

I have a problem with image in a flex container. I want it to keep ratio when the container/window height is decreased/resized down.

Sample fiddle

html,
body {
  height: 100%;
}

.wrapper {
  display: flex;
  width: 100%;
  height: 60%;
  border: 1px solid red;
}

.image-container {
  display: flex;
  align-items: center;
  max-width: 30%;
  height: 100%;
  background: green;
}

img {
  max-width: 100%;
  max-height: 100%;
}

.content {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  width: 100%;
  height: 100%;
  background: yellow;
}
<div class="wrapper">
  <div class="image-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Clouds_over_the_Atlantic_Ocean.jpg/1200px-Clouds_over_the_Atlantic_Ocean.jpg" alt="">
  </div>
  <div class="content">
    <span>Some content</span>
  </div>
</div>

When you try to do it you can see that only image's height changes but width stays the same and the image is kind of stretched.

When I delete 'display: flex' from the image container, an image resizes well. I made it flex because i wanted it to be centered.

Is there a way to keep the ratio and fluidly resize image and the rest of containers?

Asons
  • 84,923
  • 12
  • 110
  • 165
somedev
  • 11
  • 2
  • In this `fiddle` no stretched, and width and height both resized. – Pedram Dec 03 '17 at 06:17
  • Try to resize down output window. – somedev Dec 03 '17 at 06:20
  • @pedram, generally in my application I have an option that this wrapper container decreases its height when a user performs a specific action. That's why I'm talking about window resizing in this moment. When you keep decreasing height of output window you will see that width of image does not change. – somedev Dec 03 '17 at 06:27
  • You need to set `height` free, please see this [Fiddle](https://jsfiddle.net/c68v5Lot/1/) Is it okay for you? your image not square and you need set `auto` for `height` – Pedram Dec 03 '17 at 06:33
  • @pedram Not exactly. I want to achieve effect that is visible when you set image-container's display on block, just like in this [Fiddle](https://jsfiddle.net/c68v5Lot/2/) – somedev Dec 03 '17 at 06:43
  • @pedram But now an image is not centered. I could use other way to center this image but would like to keep things consistent with flex. – somedev Dec 03 '17 at 06:46
  • If your buggy behavoir is about IE , https://stackoverflow.com/questions/36822370/flexbox-on-ie11-image-stretched-for-no-reason/36828291 and your fiddle fixed ? https://jsfiddle.net/c68v5Lot/3/ Your missing rule on `img`, might just be : `flex-shrink:0;` – G-Cyrillus Dec 03 '17 at 10:21

1 Answers1

2

Just add object-fit: cover; on img tag:

img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

JSFiddle

Pedram
  • 15,766
  • 10
  • 44
  • 73
Sonia
  • 1,909
  • 1
  • 11
  • 13