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.

Box Modelhover a layer
margin
border
padding
content
Hover each layer to learn what it does.

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.

Flexbox Playgroundtoggle any property
flex-direction
flex-wrap
justify-content
align-items
A
B
C
.container { display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start; align-items: stretch; }

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.

Grid Playgroundtoggle columns and gap
grid-template-columns
gap
1
2
3
4
5
6
.container { display: grid; grid-template-columns: 1fr; gap: 6px; }

Flexbox vs Grid — when to use which

SituationUseWhy
Navbar with logo + linksFlexboxOne row, space-between
Card grid that wrapsGrid2D, auto-fit minmax
Centering a single elementFlexboxjustify + align center
Page-level layoutGridHeader / sidebar / main
Button row with icon + textFlexboxInline axis alignment
Dashboard tilesGridNamed 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.

Specificity Calculatorclick a selector to compare
/* 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; }