Skip to content Skip to sidebar Skip to footer

How To Stop Images Within A Flexbox Container Ignoring The Heigth Set By Parent?

For the past couple of days, I thought the issue I've been having was with the API that i was using but after stumbling upon this article talking about flex:1 issues I've discovere

Solution 1:

I finally found a reasonable fix not using a background image but playing further with flex box! here's my solution:

HTML

 <div className="App">
      <div className="box1">
        <img src={image} />
      </div>
      <div className="box2" />
      <div className="box3" />
    </div>

It turns out as far as I can understand images have there own unique flex-basis property based on there actual size which is different from every other element and they use this as there default flex property which they grow or shrink from, so setting this value to 0(flex-basis:0) makes it behave the same way as a regular element. The only issue with this on its own is the height of the image will stay at 0px no matter the percentage set this can simply be fixed by adding the flex-grow:1 property

Sass

.App {
  height: 100vh;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .box1{
    display: flex;
    width: 100%;
    height: 100%;
    flex-grow: 1;
    flex-basis: 0;
    background: blue;
    overflow: hidden;

    img{
      width: auto;
      height: auto;
      max-width: 100%;
      max-height: 100%;
      object-fit: cover;
      background-repeat: no-repeat;
      margin: auto;
    }
  }
  
  .box2{
    background: purple;
    height:200px; 
  }
  .box3{
    background: green;
    height: 250px;
  }
}

Here's a code sandbox demonstrating for you to play around with as this seems to be a largely unanswered question hope it helps some people who were struggling as much as I was!


Solution 2:

You can use your image as a background of the div

.box1{
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

<div className="box1" style={{background: `url(${image})`}}>

Post a Comment for "How To Stop Images Within A Flexbox Container Ignoring The Heigth Set By Parent?"