[css] Prevent content from expanding grid items

TL;DR: Is there anything like table-layout: fixed for CSS grids?


I tried to create a year-view calendar with a big 4x3 grid for the months and therein nested 7x6 grids for the days.

The calendar should fill the page, so the year grid container gets a width and height of 100% each.

.year-grid {
  width: 100%;
  height: 100%;

  display: grid;
  grid-template: repeat(3, 1fr) / repeat(4, 1fr);
}

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
}

Here's a working example: https://codepen.io/loilo/full/ryXLpO/

For simplicity, every month in that pen there has 31 days and starts on a Monday.

I also chose a ridiculously small font size to demonstrate the problem:

Grid items (= day cells) are pretty condensed as there are several hundreds of them on the page. And as soon as the day number labels become too large (feel free to play around with the font size in the pen using the buttons on the upper left) the grid will just grow in size and exceed the page's body size.

Is there any way to prevent this behaviour?

I initially declared my year grid to be 100% in width and height so that's probably the point to start at, but I couldn't find any grid-related CSS properties that would've fitted that need.

Disclaimer: I'm aware that there are pretty easy ways to style that calendar just without using CSS Grid Layout. However, this question is more about the general knowledge on the topic than solving the concrete example.

This question is related to css grid-layout css-grid

The answer is


The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:


.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;  
}

.day-item-wrapper {
  position: relative;
}

.day-item {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 10px;

  background: rgba(0,0,0,0.1);
}

https://codepen.io/bjnsn/pen/vYYVPZv


The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.