After considering your specific requirements:
- You need a grid that can have a varying number of rows.
- Each row should adjust its size automatically.
- The last row must consume all remaining space available.
For achieving this layout, Flexbox is an excellent choice and might be the perfect solution based on additional requirements. An example code snippet is provided below.
If you are set on using Grid Layout, it may not fulfill your needs completely. As per the current Level 1 specification, it cannot handle such demands.
The closest implementation in Grid would look like this:
grid-template-rows: repeat(auto-fit, minmax(auto, 1px)) 1fr;
Unfortunately, this syntax is unsupported by the current grid specifications.
repeat(auto-fit, auto) 1fr
You attempted to use this code, but it's invalid because auto
and fr
cannot be combined with auto-fit
.
7.2.2.1. Syntax of
repeat()
When using automatic repetitions (auto-fill
or auto-fit
), intrinsic or flexible sizes cannot be mixed.
Examples of intrinsic sizing functions include min-content
, max-content
, auto
, fit-content()
.
Flexible sizing functions encompass <flex> values (e.g., fr
).
To address the limitation with auto
, you could try something like this:
repeat(auto-fit, minmax(auto, 1px)) 1fr
minmax(min,max)
This function defines a size range between min and max, inclusive.
If max < min, then max is neglected and minmax(min,max)
is treated as min.
A <flex>
value can only act as the track’s flex factor and cannot be used as a minimum.
This method correctly sizes your rows based on content, regardless of whether the container has a default height setting or specified height
/ min-height
. View the demo for clarification.
However, the issue with the last row remains unresolved due to the invalid
1fr</code], causing the entire rule to fail. A working solution would utilize:</p>
<h2><code>repeat(auto-fit, minmax(auto, 1px)) 10em
In this scenario, the auto-fit
does not behave as expected—the 10em
applies to the second row instead. Refer to the demo for details.
This setup also encounters issues when the container specifies a height
or min-height
. Review the demo for more insights.
Despite the widespread availability of CSS Grid Layout, Flexbox still serves as the superior option in certain scenarios.
It meets all your criteria with straightforward and concise code:
article {
display: flex;
flex-direction: column;
height: 100vh;
}
section:last-child {
flex-grow: 1;
}
section {
/* flex-basis: auto <-- this is a default setting */
margin-bottom: 10px;
background-color: lightgreen;
}
body {
margin: 0;
}
<article>
<section>text text text</section>
<section>text text text text text text text text text text text text ...
</section>
<section>text text text ...</section>
<section>text text text ...</section>
<section>text text text ...</section>
</article>