appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

CSS selectors and the box model

Lesson 3 of 511 minBeginner

Choose which elements to style and understand the space every element takes.

CSS (Cascading Style Sheets) controls how HTML looks. A rule has a selector and a block of declarations.

style.css
h1 {
  color: #17141f;
  font-size: 2rem;
}

Link the file in the head with <link rel="stylesheet" href="style.css">.

Common selectors

SelectorMatches
pevery paragraph
.cardelements with class="card"
#topthe element with id="top"
nav alinks inside a nav
a:hovera link while the mouse is over it

Prefer classes. When two rules conflict, the more specific selector wins, and if they are equal the later rule wins. This is the cascade.

The box model

Every element is a box made of four layers, from inside out: content, padding, border and margin.

* { box-sizing: border-box; }
.card {
  width: 20rem;
  padding: 1rem;
  border: 2px solid #17141f;
  margin: 1rem auto;
}

NoteWith box-sizing: border-box, width includes padding and border. Without it, the padding is added on top and layouts break in surprising ways. Most projects set it for everything.

Use relative units: rem follows the root font size, % follows the parent and px is fixed. Relative units respect the font size that the visitor chose.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which selector matches elements with class="card"?
2. What are the layers of the box model from the inside out?
3. What does box-sizing: border-box change?