CodeMIRAI
0 XP

Selectors

2 min read 4 runnable examples Quiz included

A selector decides which elements a rule styles. Learning selectors is learning to point at exactly the right things.

The basic selectors

SelectorTargetsExample
pevery <p> elementp { }
.noteevery element with class="note".note { }
#headerthe element with id="header"#header { }
*every element* { }
h1, h2every h1 and every h2h1, 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

SelectorTargets
nav aany <a> inside a <nav> (descendant)
ul > li<li> that are direct children of a <ul>
h2 + pthe <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:

Wins against everything below itstyle="..."1, 0, 0, 0inline style#header0, 1, 0, 0id.btn [type] :hover0, 0, 1, 0class, attribute, pseudo-classp h1 ::before0, 0, 0, 1element, pseudo-element#nav .item a scores 0,1,1,1: compare from the left; on a tie, the later rule wins
When rules clash, the more specific selector wins, whatever order they're written in. !important overrides all of this, so save it for emergencies.
  1. inline styles beat everything below,
  2. ids (#header) beat classes,
  3. classes, attributes and pseudo-classes (.note, [type], :hover) beat elements,
  4. 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.