Bence Mányoki
Bence Mányoki

Reputation: 317

How do I force an image in CSS to obey parent flexbox section height?

The problem has been stated very clearly in this question: Flexbox - Img height conflict ...but: the accepted answer is not so useful, in my case.

Solution #1: The absolute - relative. This works great, size-wise, but fiddles with the ZIndex. That is not a desired side effect for me, because it really breaks my site since I have a lot of overlapping elements.

Solution 2#: The min-height: 0 & height: 100& answer is almost totally useless, it helps a bit, but still not there, compared to the absolute pos. stuff.

Is there a way to achieve a vertical flexbox, with 2 equal sized sections, where one contains an Img?

Here's a snippet what would be the desired outcome. As you can see, the sizing works perfectly, but the zindex doesn't, the yellow div should cover the image too.

img{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.cattainer{
  display: flex;
  background: blue;
  flex-direction: column;
  flex: 1;
  position: relative;
}

.overlay{
  flex: 1;
  display: grid;
  grid-template-rows: 100%;
  grid-template-columns: 100%;
}

.overlayItem{
  grid-area: 1/1/auto/auto;
}
<html style="height: 100%; width: 100%">
   <head></head>
   <body style="
       width: 100%;
       height: 100%;
       display: flex;
      ">
         
      <div class="overlay">
        
         <div class="overlayItem" style="display: flex;flex: 1;background: blue;flex-direction: column;">
           <div style="background: red;flex: 1;"></div>
           <div class="cattainer">
              <img src="https://cdn.mos.cms.futurecdn.net/VSy6kJDNq2pSXsCzb6cvYF.jpg" >
           </div>
        </div>
        
        <div class="overlayItem" style="background: yellow;flex: 1;"></div>
      </div>
   </body>
</html>

Upvotes: 1

Views: 87

Answers (1)

Sean Stopnik
Sean Stopnik

Reputation: 1868

You can use:

img {
  object-fit: cover;
}

Though your example image is extremely large, 2800px X 1575px. Might want to use an image that's sized closer to the dimensions of the box? Just a thought.

Upvotes: 1

Related Questions