What Is CSS? Selectors and the Cascade
CSS (Cascading Style Sheets) controls how HTML looks: colors, fonts, spacing, layout, and more. HTML says what something is, CSS says how it appears.
Three ways to add CSS
An external stylesheet, linked from <head>, is almost always the right choice: it's cacheable and keeps style separate from structure.
Selectors
p { color: navy; } /* every <p> */
.card { padding: 16px; } /* every element with class="card" */
#logo { width: 120px; } /* the one element with id="logo" */
nav a { text-decoration: none; } /* every <a> inside a <nav> */
| Selector | Matches |
|---|---|
element | Every element of that tag, e.g. p, h1 |
.class | Every element with that class attribute |
#id | The single element with that id |
a b | Every b element nested anywhere inside an a |
The cascade and specificity
When two rules target the same element and property, CSS decides the winner using specificity: IDs beat classes, classes beat plain elements. If specificity ties, the rule that appears later in the stylesheet wins.
p { color: navy; } /* specificity: 0-0-1 */
.highlight { color: gold; } /* specificity: 0-1-0, wins over the rule above */
#alert { color: red; } /* specificity: 1-0-0, wins over both */
WARNING
!important overrides normal specificity entirely and is very hard to override again later. Treat it as a last resort, almost every specificity fight can be solved by writing a more specific (or simpler) selector instead.