Implementing a dynamic number of columns with CSS Grid is a breeze.
.grid {
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
// These .cells are beautifully aligned
<div class="grid">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
However, what about more intricate layouts that include a header and/or footer?
// This approach does not work
.grid {
grid-template-columns: 1fr, repeat(auto-fit, minmax(100px, 1fr)), 1fr;
}
<div class="grid">
<header></header>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<footer></footer>
</div>
It seems that achieving this dynamic nature without creating a new grid by wrapping the cells in a container is a challenge, which goes against the purpose of adopting grid in the first place.
Using template areas also does not provide a solution as the header and footer are optional.
Is it feasible to achieve this dynamic behavior with CSS Grid?
UPDATE
After some exploration, it appears that achieving this layout is indeed not possible using CSS Grid alone. I ended up using JavaScript to modify a CSS custom property to update the grid columns dynamically.
ANSWER
The example by Paulie_D only serves to highlight the issue rather than resolve it.
Essentially, achieving a dynamic layout with CSS Grid is not feasible in most scenarios, as specific columns need to be defined. This limitation somewhat diminishes the advantages of using CSS Grid in my opinion.
// HTML
<div class="grid">
<header></header>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<footer></footer>
</div>
// CSS
.grid {
grid-template-columns: 1fr 1fr 1fr;
}
header,footer {
grid-span: 1 / -1;
}