Selectors in depth

Lesson 2 of 14 9 min read Free lesson

Target exactly the elements you want with type, class, id, group, descendant and pseudo-class selectors.

The selectors you will use every day

SelectorPicksExample
pevery <p>p { line-height: 1.6; }
.cardelements with class="card".card { padding: 1rem; }
#menuthe element with id="menu"#menu { display: flex; }
h1, h2every h1 and every h2h1, h2 { color: navy; }
nav alinks inside a navnav a { text-decoration: none; }
ul > lili that are direct children of ulul > li { margin: 4px; }
*every element* { box-sizing: border-box; }

Pseudo-classes: elements in a state

CSS Try it in CodeLab
a:hover { color: #FFA500; }          /* mouse over the link */
input:focus { outline: 3px solid #FFA500; } /* field being typed in */
li:first-child { font-weight: bold; }  /* first item of a list */
li:nth-child(even) { background: #f5f5f5; } /* every second item */
button:disabled { opacity: .5; }

Which rule wins? (the cascade)

When two rules set the same property on the same element:

  1. The more specific selector wins: an id beats a class, a class beats an element name.
  2. If they are equally specific, the rule written later wins.
CSS Try it in CodeLab
p { color: black; }
.intro { color: navy; }   /* wins over p: a class is more specific */
#lead { color: orange; }  /* wins over .intro: an id is more specific */

Exercise

Make every link inside the nav white, and orange when hovered.

Starting code Try it in CodeLab
nav a {
}
Show a possible solution
Solution
nav a {
  color: #ffffff;
}
nav a:hover {
  color: #FFA500;
}

Check your understanding

Quick check

Which selector picks elements with class="note"?

Quick check

"nav a" picks…

Quick check

Two rules set the colour of the same element: ".intro" and "p". Which wins?

Hi there! đź‘‹ Have a question about the courses or joining the class? Ask me.