Szabolcs Andrasi
Szabolcs Andrasi

Reputation: 93

CSS grid row overflows its container vertically

I would like to have a grid layout on a page where the grid stretches out to the entire viewport, and the rows have a minimum height. The simplest example would be a grid with a single cell (see code snippet below).

The problem I am having is that when the height of the viewport is less than the defined minimum row-height, the row vertically overflows its container. With the added red and green borders in the below example it's visible that the row's height isn't going below the defined 500 pixels, but the grid-container is still sized to the viewport which is now shorter than 500 pixels.

If I remove the height CSS attribute from the grid class, the container doesn't shrink below its content, but it also doesn't fill out the vertical space when the viewport is taller than 500 pixels. Since I want the grid to fill the entire page, I need the height CSS attribute. I've also added the min-height: fit-content attribute which is supposed to prevent the used value of the height property from becoming smaller than the value specified for min-height but it doesn't work (not with the defined fit-content value - it works as expected with an exact value, for example 300px).

In a similar question the culprit was the percentage values used for the gaps, but in this case there is nothing relatively sized. Even if replace the grid-template-rows: minmax(500px, 1fr); property with the fixed grid-template-rows: 500px;, it still behaves the same way.

body {
  margin: 0;
}

.grid {
  display: grid;
  grid-template-rows: minmax(500px, 1fr);
  height: 100vh;
  min-height: fit-content;
  width: 100vw;
}

.bordered {
  border: 10px solid green;
}
<div class="grid bordered" style="border-color: red;">
  <div class="bordered">Some content</div>
</div>

What I would like to have is a grid that fills out the entire viewport and where the grid-container is never smaller than its content. What am I missing?

Upvotes: 4

Views: 1906

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45865

Something to know is that as soon as a min height of a row, or the combined height of multiple rows, is greater than the height of the viewport, you will have a scroll. Beyond that, the snippet below, I hope does what you are looking for. I added comments in the code.

/* lines I added */
*{
  box-sizing: border-box;
}

body {
  margin: 0;
}
 
.grid {
  display: grid;
  /* 100 is for the small viewport here in the code snippet */
  grid-template-rows: repeat(auto-fit, minmax(100px, 1fr));
  min-height : 100vh;
  
}

.bordered {
  border: 10px solid green;
}
<div class="grid bordered" style="border-color: red;">
  <div class="bordered">Some content</div>
</div>

Upvotes: 3

Related Questions