CSS selectors and the box model
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.
h1 {
color: #17141f;
font-size: 2rem;
}Link the file in the head with <link rel="stylesheet" href="style.css">.
Common selectors
| Selector | Matches |
|---|---|
p | every paragraph |
.card | elements with class="card" |
#top | the element with id="top" |
nav a | links inside a nav |
a:hover | a 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.