For years, web designers built layouts with tables, then with floats and clearfix hacks. Those days are over. Every modern browser supports two layout systems that were designed for the job: flexbox and grid. If you are new to CSS, read what CSS is first.
Flexbox: one direction at a time
Flexbox places items in a row or a column and decides how they share the available space. It is perfect for navigation bars, button groups, centring something and small components.
.menu {
display: flex;
gap: 1rem; /* space between items */
align-items: center; /* vertical alignment */
justify-content: space-between; /* spread items out */
flex-wrap: wrap; /* allow a new line on small screens */
}The flexbox properties you need
flex-direction–row(default) orcolumn.justify-content– alignment along the main direction:flex-start,center,space-between…align-items– alignment across it:stretch,center,baseline…flex: 1on an item – let it grow to fill the remaining space.
/* Centre anything, horizontally and vertically */
.hero {
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
}Grid: rows and columns together
CSS grid divides space into rows and columns, and places items in the cells. It shines for page layouts, galleries and card overviews.
.page {
display: grid;
grid-template-columns: 1fr 300px; /* content + sidebar */
gap: 2rem;
}
@media (max-width: 800px) {
.page { grid-template-columns: 1fr; } /* stack on small screens */
}The fr unit means “a fraction of the free space”. 1fr 2fr makes the second column twice as wide as the first.
A responsive card grid in one line
This is probably the most useful line of CSS of the past decade. It fits as many columns of at least 16rem as there is room for, and stretches them to fill the row – no media queries needed:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
gap: 1.5rem;
}Flexbox or grid?
| Situation | Best choice |
|---|---|
| Navigation bar, toolbar, tags | Flexbox |
| Centring one element | Flexbox (or grid with place-items: center) |
| Page with header, sidebar and footer | Grid |
| Cards that must line up in columns | Grid |
| Items with unknown widths that should wrap | Flexbox with flex-wrap |
For a deep dive, the MDN guide to CSS layout is the best free reference available.
Frequently asked questions
Should I learn flexbox or grid first?
Start with flexbox: it solves everyday problems like navigation bars and centring. Learn grid next for page layouts and card grids. You will use both, often on the same page.
Do I still need floats?
Only for what they were made for: letting text flow around an image. For layout, flexbox and grid are simpler and more robust.