CSS Layout
CSS layout is the system for placing elements on a page. For most of the web's history, developers used floats and tables — hacks never meant for layout. Flexbox arrived in 2012 and Grid in 2017. Together they cover nearly every layout pattern you will ever need.
The distinction is simple: Flexbox is one-dimensional — it controls items along a single axis. Grid is two-dimensional — it controls rows and columns simultaneously. Choose based on whether your layout thinks in lines or planes.
The box model
Before either system, every element is a box. Understanding that box is prerequisite to understanding why layouts break. Hover each layer below to see what it controls.
Flexbox
Flexbox distributes items along a single axis. The parent becomes a flex container; its direct children become flex items. Toggle the properties below and watch the layout update live.
Grid
Grid thinks in two dimensions at once. You define columns and rows on the parent; items place themselves or you place them explicitly. The most powerful single line in CSS layout:
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
This creates as many columns as fit, each at least 200px wide, sharing remaining space equally. No media queries needed.
Flexbox vs Grid — when to use which
| Situation | Use | Why |
|---|---|---|
| Navbar with logo + links | Flexbox | One row, space-between |
| Card grid that wraps | Grid | 2D, auto-fit minmax |
| Centering a single element | Flexbox | justify + align center |
| Page-level layout | Grid | Header / sidebar / main |
| Button row with icon + text | Flexbox | Inline axis alignment |
| Dashboard tiles | Grid | Named areas, explicit placement |
CSS specificity
When two rules target the same element, the browser picks the one with higher specificity. The scoring system has three buckets — IDs, classes, and elements — read like a three-digit number.
/* 0-0-1 — lowest weight */
p { color: gray; }
/* 0-1-0 — beats element selectors */
.title { color: black; }
/* 1-0-0 — beats everything except inline + !important */
#hero { color: red; }
/* nuclear option — avoid */
.btn { color: blue !important; }
Common layout patterns
/* Holy grail layout */
.page {
display: grid;
grid-template:
"header header header" auto
"sidebar main aside" 1fr
"footer footer footer" auto
/ 200px 1fr 200px;
}
/* Centred container */
.container {
max-width: 800px;
margin: 0 auto;
padding: 0 1rem;
}
/* Sticky footer */
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main { flex: 1; }