← Learn
CSS2 min read·22 Oct 2026

CSS: the box model, Flexbox and Grid — the three things that make layouts click

Most CSS confusion is three concepts. Understand them and centring a div stops being a joke.

HCHandwrittenCode team
Study Delight Publications, Delhi
CSS: the box model, Flexbox and Grid — the three things that make layouts click

Students memorise CSS properties and still cannot lay out a page. That is because layout is not about properties — it is about three models. Once you can picture them, the properties are obvious.

1. The box model

Every element is a box: content → padding → border → margin, inside out. Width by default is the content only, which is why boxes overflow. The fix, on every project:

* { box-sizing: border-box; }

Now width: 300px means the whole box is 300px including padding and border. The exam question "explain the box model with a diagram" is the four nested rectangles with those labels.

2. Flexbox — one direction at a time

Put display: flex on the parent. Children line up in a row (or a column with flex-direction: column). Then:

  • justify-content — spacing along the main axis (start, center, space-between)
  • align-items — alignment on the cross axis
  • gap — space between children
  • flex: 1 on a child — let it grow
.nav { display: flex; justify-content: space-between; align-items: center; gap: 16px; }
.center { display: flex; justify-content: center; align-items: center; height: 100vh; }

That second rule is the famous "centre a div" — two lines.

3. Grid — two directions at once

Use Grid when you have rows and columns: a photo gallery, a dashboard, a page with header/sidebar/main/footer.

.gallery { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
.page {
  display: grid;
  grid-template-areas: "header header" "sidebar main" "footer footer";
  grid-template-columns: 240px 1fr;
}

What else the paper asks

  • Three ways to add CSS — inline, internal, external — and why external wins.
  • Selectors — element, class, id, descendant, child, attribute, pseudo-classes (:hover, :nth-child), pseudo-elements (::before).
  • Specificity — inline > id > class > element; !important and why not to use it.
  • Positioning — static, relative, absolute, fixed, sticky, and what each is relative to.
  • Units — px, %, em, rem, vw, vh.
  • Responsive design — @media (max-width: 768px), mobile-first.
  • Transitions and simple animations with @keyframes.

Build one page with a flex navbar, a grid gallery and a media query, and you have touched everything above.

The CSS Simplified Handwritten Notes (208 pages) draw the box model, every Flexbox and Grid property, and the before/after of each rule.