Selectors
A selector decides which elements a rule styles. Learning selectors is learning to point at exactly the right things.
The basic selectors
| Selector | Targets | Example |
|---|---|---|
p | every <p> element | p { } |
.note | every element with class="note" | .note { } |
#header | the element with id="header" | #header { } |
* | every element | * { } |
h1, h2 | every h1 and every h2 | h1, h2 { } |
HTML
<style>
p { color: #444; }
.highlight { background: #fff4dc; }
#intro { font-weight: bold; }
h2, h3 { color: #5a48f5; font-family: system-ui; }
</style>
<h2>Selectors</h2>
<p id="intro">This paragraph is targeted by its id.</p>
<p class="highlight">This one by its class.</p>
<h3>And headings by grouping</h3>Combinators: elements in relation to others
| Selector | Targets |
|---|---|
nav a | any <a> inside a <nav> (descendant) |
ul > li | <li> that are direct children of a <ul> |
h2 + p | the <p> immediately after an <h2> |
HTML
<style>
.menu a { color: #0aa9cf; text-decoration: none; margin-right: 12px; }
.list > li { list-style: square; }
h3 + p { font-style: italic; }
</style>
<nav class="menu"><a href="#">Home</a><a href="#">Courses</a></nav>
<h3>Title</h3>
<p>The paragraph right after a heading is italic.</p>
<p>This one isn't.</p>
<ul class="list"><li>Direct child: square bullet</li></ul>Attribute selectors
HTML
<style>
input[type="email"] { border: 2px solid #5a48f5; }
a[target="_blank"]::after { content: " ↗"; }
</style>
<input type="text" placeholder="text"> <input type="email" placeholder="email"><br><br>
<a href="#" target="_blank">External link</a>Specificity: who wins?
When two rules conflict, the more specific selector wins, regardless of order:
- inline styles beat everything below,
- ids (
#header) beat classes, - classes, attributes and pseudo-classes (
.note,[type],:hover) beat elements, - element selectors (
p) are the weakest.
HTML
<style>
#main { color: crimson; }
.text { color: teal; }
p { color: gray; }
</style>
<p id="main" class="text">Crimson: the id wins.</p>
<p class="text">Teal: the class beats the element.</p>Finished this lesson?Mark it complete to earn +20 XP and move your progress on.