CSS controls how HTML elements look on screen. Before diving into layouts, you need a solid understanding of how styles are selected, calculated, and applied.
Selectors
Selectors target the elements you want to style. Here are the ones you will use most:
Specificity
When multiple rules target the same element, specificity determines which one wins. Think of it as a three-part score: (ID, Class, Element).
| Selector | Specificity | Score |
|---|---|---|
p | (0, 0, 1) | 1 |
.card | (0, 1, 0) | 10 |
#hero | (1, 0, 0) | 100 |
.card p | (0, 1, 1) | 11 |
#hero .title | (1, 1, 0) | 110 |
Practical rules:
- Prefer classes over IDs for styling.
- Avoid
!important— it breaks the cascade and makes debugging painful. - Keep selectors short.
.card-titlebeats.sidebar .card .card-body .card-title.
The Box Model
Every element is a rectangular box with four layers:
┌─────────── margin ───────────┐
│ ┌──────── border ──────────┐ │
│ │ ┌────── padding ───────┐ │ │
│ │ │ │ │ │
│ │ │ content │ │ │
│ │ │ │ │ │
│ │ └──────────────────────┘ │ │
│ └──────────────────────────┘ │
└──────────────────────────────┘By default, width sets the content width, and padding/border are added on top. This is confusing, so always use border-box:
With border-box, a width: 300px element stays 300px total, including padding and border.
Units
Choose the right unit for the job:
| Unit | Use for | Base |
|---|---|---|
px | Borders, shadows, fine details | Absolute |
rem | Font sizes, spacing, widths | Root font size (usually 16px) |
em | Padding/margin relative to current font | Current element's font size |
% | Widths relative to parent | Parent dimension |
vw / vh | Viewport-relative sizing | Viewport width/height |
dvh | Full-height layouts on mobile | Dynamic viewport height |
Tip: Use rem for most spacing. It scales consistently and makes responsive adjustments easy — change the root font size, and everything updates.
Custom Properties (CSS Variables)
Custom properties let you define reusable values and swap them dynamically:
Custom properties cascade and inherit, making them perfect for theming. Change the variable in one place, and every element using it updates.
Practical Reset
A minimal reset gives you a consistent starting point:
This reset eliminates default margins, makes images responsive, and ensures form elements inherit font styles.