Mastering the CSS Grid Layout Algorithm
For years, we hacked layouts with floats, then we got Flexbox for one-dimensional layouts. But in 2018, CSS Grid is the definitive way to build two-dimensional layouts on the web. It's not just a syntax; it's a completely different layout engine.
The Power of fr
The fractional unit (fr) is the heart of Grid's flexibility. It represents a fraction of the free space in the grid container.
.container {
display: grid;
grid-template-columns: 200px 1fr 2fr;
grid-gap: 20px;
}
In this setup, the first column is fixed at 200px. The remaining space is divided into 3 units (1 + 2), where the second column gets 1/3 and the third gets 2/3.
Named Areas vs. Line Numbers
One of the most revolutionary features is grid-template-areas. It allows you to visualize your layout directly in your CSS.
.container {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-rows: auto 1fr auto;
grid-template-columns: 150px 1fr;
height: 100vh;
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
The minmax() Function
Grid introduces minmax(), allowing you to define a range for track sizes. This is crucial for responsive design without media queries.
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
This single line creates a responsive card layout where cards are at least 250px wide but will grow to fill the available space. If the container shrinks, cards automatically wrap.
The Explicit vs. Implicit Grid
If you place an item outside the defined tracks, Grid creates an implicit grid to hold it. You can control these tracks with grid-auto-rows and grid-auto-columns.
CSS Grid isn't just a replacement for Bootstrap; it's the end of layout frameworks as we know them.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development