Search code examples
htmlcssflexboxcss-grid

Equal height for rows of CSS Grid or Flexbox with non-infinite height


Note that this answer works and explains why it works for infinite height CSS grid. In my case, the height is limited (which could be 100vh or due to flex-grow but it's not infinite).

Let's say I have a certain space for a grid (decided by a flex box which is the remaining space of whatever remaining of the screen). I want it to be divided into two equal rows. The top one should be an img with object-fit: scale-down that take up all 50% height and at most 100% width and the bottom row should be some random text. Problem is, when the img is bigger, it takes up additional space (see example below).

Is it possible to divide a CSS grid or flex box (or any kind of display) into two strictly equal rows?

body {
  height: 100vh;
  width: 500px;
  display: flex;
  margin: 0;
  padding: 0;
}

.grid {
  height: 100%;
  width: 100%;
  
  display: grid;
  grid-template-rows: 1fr 1fr;
  
  background-color: cornflowerblue;
  
  padding: 1rem;
}

img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: scale-down;
}

.content {
  background-color: black;
  color: white;
}
<div class="grid">
  <img src="https://placehold.co/600x400" />
  <div class="content">Another content</div>
</div>


Solution

  • If you put the img inside a div and set the img position: absolute, the setting seems to work OK.

    body {
      height: 100vh;
      width: 700px;
      display: flex;
      margin: 0;
      padding: 0;
    }
    
    .grid {
      height: 100%;
      width: 100%;
      
      display: grid;
      grid-template-rows: 1fr 1fr;
      
      background-color: cornflowerblue;
      
      padding: 1rem;
    }
    
    .grid > .img-container {
      position:relative;
      background:pink;
    }
    
    img {
      display: block;
      position: absolute;
      width: 100%;
      height: 100%;
      object-fit: scale-down;
    }
    
    .content {
      background-color: black;
      color: white;
    }
    <div class="grid">
      <div class="img-container">
        <img src="https://placehold.co/600x400" />
      </div>
      <div class="content">Another content</div>
    </div>