2

I have a container with a title and an image. I want the image to take the remaining space in the container so im using flex-grow. The container takes the remaining space but when I add the image, they image extends over the container.

Setting opacity of innerWrapper to 50% to see how the image extends past the container.

#container {
  width: 500px;
  height: 200px;
  background-color: black;
  display: flex;
  flex-direction: column;
}

#title {
  color: white;
  font-weight: bold;
  background-color: gray;
  font-size: 28px;
}

#imageWrapper {
  background-color: red;
  width: 100%;
  flex: 1;
  opacity: 50%;
}

#image {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
<div id="container">
  <div id="title">Title</div>
  <div id="imageWrapper">
    <img id="image" src="https://estnn.com/wp-content/uploads/2020/08/FNC-header-800x450.png">
  </div>
</div>
Alvaro Bataller
  • 487
  • 8
  • 29
  • You just need `overflow: hidden` on your container. But you really should not be using IDs as the selectors in your CSS like that. It's much better to use classes. – JHeth Jun 17 '21 at 06:39
  • Setting overflow to hidden is going to crop the bottom of my image, i want the image to be cropped both top and bottom. – Alvaro Bataller Jun 17 '21 at 06:58
  • Ah ok, then try setting `overflow: hidden` on your `#imageWrapper` container, that should cut off a little of the top and bottom since you have `object-fit: cover` on the image. – JHeth Jun 17 '21 at 07:05

1 Answers1

-1

After a lot of fiddling, adding min-height: 0; and flexing also #imageWrapper seems to help...

It looks like min-height is set to auto by default.

#container {
  width: 500px;
  height: 200px;
  background-color: black;
  display: flex;
  flex-direction: column;
}

#title {
  color: white;
  font-weight: bold;
  background-color: gray;
  font-size: 28px;
}

#imageWrapper {
  display: flex;
  background-color: red;
  width: 100%;
  flex: 1;
  min-height: 0;
  opacity: 50%;
}

#image {
  object-fit: cover;
  width: 100%;
}
<div id="container">
  <div id="title">Title</div>
  <div id="imageWrapper">
    <img id="image" src="https://estnn.com/wp-content/uploads/2020/08/FNC-header-800x450.png">
  </div>
</div>
Pan Vi
  • 627
  • 6
  • 17
  • This still doesnt work, when you set the height to 100% the imageWrapper takes the height of its parent which includes the title height. So the image still extends pass the bottom of the container. You can see this by setting the opacity of the innerWrapper to 50% – Alvaro Bataller Jun 17 '21 at 06:20