TutreNews Learn

Rules, selectors and the cascade

Selectors

Goal: Target elements with type, class, id, descendant, child and pseudo-class selectors · 11 min

Selectors decide which elements a rule applies to.

selectorexampleselects
typepall <p> elements
class.noteelements with class="note"
id#headerthe element with id="header" (unique)
universal*everything
grouph1, h2, h3any of them
descendantnav aevery <a> anywhere inside a <nav>
childul > li<li> that are direct children of <ul>
adjacent siblingh2 + pthe <p> right after an <h2>
attributea[href^="https"]links whose href starts with https
pseudo-classa:hover, li:first-childan element in a certain state or position

Combining without a space means "both at once": p.note is a <p> with class note, while p .note (with a space) is any .note inside a <p>.

Classes are the workhorse: reusable, any number per element (class="card featured"). IDs must be unique; use them rarely for styling.

Pseudo-classes worth knowing: :hover (mouse over), :focus (keyboard focus), :first-child, :last-child, :nth-child(2n) (every second one).

Worked example: Which elements are selected?

  1. HTML: <ul><li>A</li><li class="sale">B</li></ul>
  2. "li" selects A and B; ".sale" selects only B; "li:first-child" selects only A.
  3. "ul > li.sale" selects B: a direct child li that has class sale.
<ul>
  <li>A</li>
  <li class="sale">B</li>
</ul>