Selectors & Specificity
What CSS does
CSS (Cascading Style Sheets) controls how HTML looks: colours, fonts, spacing and layout.
selector { property: value; }
h1 { color: navy; font-size: 2rem; }
Add CSS with a <link rel="stylesheet" href="style.css"> in <head> (best), a <style> block, or the inline style="" attribute (avoid).
Selectors
| Selector | Matches |
|---|---|
p | all <p> elements |
.card | class="card" |
#header | id="header" |
nav a | <a> inside <nav> (descendant) |
ul > li | direct children only |
a:hover, input:focus, li:nth-child(2) | states and positions (pseudo-classes) |
p::first-line, .btn::before | parts of elements (pseudo-elements) |
input[type="email"] | attributes |
The cascade: who wins?
When rules conflict, the browser decides by:
- Importance:
!important(avoid using it). - Specificity: inline style >
#id>.class/:hover/[attr]>element. - Order: later rules win when specificity is equal.
Inheritance
Text properties (color, font-family, line-height) are inherited by children; box properties (margin, border) aren't.
💡 Style mostly with classes. They're reusable and keep specificity low and predictable.
Example
<style>
p { color: gray; } /* element: lowest */
.note { color: green; } /* class beats element */
#special { color: crimson; } /* id beats class */
nav a:hover { text-decoration: underline; }
li:nth-child(odd) { background: #f3f4f6; }
</style>
<p>Gray paragraph</p>
<p class="note">Green note</p>
<p class="note" id="special">Crimson (id wins)</p>
<ul>
<li>One</li><li>Two</li><li>Three</li>
</ul>