The CSS Grid Layout specification is maturing and the first browsers are implementing support. An end to hacks with floats and flexbox for complex layouts — a guide to CSS Grid.
From Tables Through Floats to Grid¶
The history of CSS layout is a history of hacks. Table-based layouts in the 90s, float-based layouts in the 2000s, flexbox for one-dimensional layouts. CSS Grid finally brings a native two-dimensional layout system.
Flexbox solves a row or a column. Grid solves rows AND columns simultaneously. We can finally build complex layouts without positioning tricks.
CSS Grid Basics¶
You define a grid on the container:
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: auto 1fr auto;
grid-gap: 20px;
min-height: 100vh;
}
.header { grid-column: 1 / -1; }
.sidebar { grid-column: 1; }
.main { grid-column: 2; }
.aside { grid-column: 3; }
.footer { grid-column: 1 / -1; }
The fr unit (fraction) distributes free space. grid-template-areas enables named regions for even more readable code.
Grid Template Areas¶
Named areas are the most intuitive way to define a layout:
.layout {
display: grid;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
}
.header { grid-area: header; }
.nav { grid-area: nav; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }
For responsive design it is enough to redefine grid-template-areas in a media query — a complete layout change without touching the HTML.
Support and Adoption¶
CSS Grid is still in the implementation phase:
- Chrome/Firefox — behind a flag, full support expected in 2017
- Edge — older specification with the -ms- prefix
- Safari — in preparation
It is still too early for production use, but experiment and prepare. Grid and Flexbox complement each other — Grid for page layout, Flexbox for component-level layouts.
Conclusion: A Revolution in CSS Layout¶
CSS Grid is the biggest shift in CSS layout in the last 20 years. Once it is fully supported, it will eliminate the need for CSS frameworks like Bootstrap for grid systems. Start experimenting today so you are ready for tomorrow.
Need help with implementation?
Our experts can help with design, implementation, and operations. From architecture to production.
Contact us