Grid items that limit content expansion
P粉199248808
2023-08-20 19:49:37
<p><strong>TL;DR:</strong> Is there a property similar to <code>table-layout: fixed</code> for CSS grid layout? </p>
<hr />
<p>I'm trying to create a year view calendar with a large 4x3 grid for the months and nested inside is a 7x6 grid for the dates. </p>
<p>The calendar should fill the entire page, so the width and height of the year grid container are set to 100%. </p>
<pre class="brush:php;toolbar:false;">.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);
}</pre>
<p>Here is a working example: https://codepen.io/loilo/full/ryXLpO/</p>
<p>For simplicity, each month in this example has 31 days and starts on Monday. </p>
<p>I also chose a very small font size to demonstrate the problem: </p>
<p>The grid items (i.e. date cells) are very compact since there are hundreds of date cells on the page. And once the date labels get too big (feel free to use the buttons in the upper left corner to adjust the font size in the example), the grid grows and exceeds the bounds of the page. </p>
<p>Is there a way to prevent this behavior? </p>
<p>I originally set the width and height of the year grid to 100%, so that might be the place to start, but I can't find any grid-related CSS properties to satisfy this need. </p>
<p><em>Disclaimer: </em>I know there are easy ways to style this calendar without using CSS Grid layout. However, this question is more about general knowledge of the topic rather than addressing specific examples. </p>
The previous answers are very good, but I also want to mention that for grids there is an equivalent way of fixing the layout, you just need to case your tracks as
minmax(0, 1fr )
instead of1fr
.By default, the size of a grid item cannot be smaller than the size of its content.
The initial sizes of grid items are
min-width: auto
andmin-height: auto
.You can do this by setting the grid items to
min-width: 0
,min-height: 0
oroverflow
(exceptvisible# any value other than ##) to override this behavior.
From specification:
Here is a more detailed explanation that covers flex items, but also applies to grid items:potential issues with nested containers and known rendering differences between major browsers.
To fix your layout, make the following adjustments to your code:
jsFiddle Demonstration
1fr
The above solution operates on the grid item level. For container-level solutions, see the following articles:and
minmax(0, 1fr)