Lesson 47 +10 XP

Pseudo-classes

Pseudo-classes

Pseudo-classes match a STATE of an element, hover, focus, first-child, nth.

The big ones

a:hover { color: hotpink; }        /* mouse over */
input:focus { outline: 2px solid; } /* keyboard focus */
a:active { }                        /* being clicked */
a:visited { }                       /* already clicked */

Structural ones

Position based:

li:first-child { }      /* first child */
li:last-child { }       /* last child */
li:nth-child(2) { }     /* 2nd child */
li:nth-child(odd) { }   /* 1st, 3rd, 5th... */
li:nth-child(even) { }  /* 2nd, 4th... */
p:first-of-type { }     /* first <p> in parent */

Form states

input:required { }       /* required fields */
input:optional { }       /* optional fields */
input:disabled { }       /* greyed-out */
input:enabled { }
input:checked { }        /* ticked checkbox */
input:focus { }
:valid / :invalid        /* valid/invalid values */
:placeholder-shown { }   /* showing placeholder */

Not(), is(), has()

Powerful modern tools:

:not(p) { }              /* everything not p */
:is(h1, h2, h3) { }      /* any of these */
div:has(> img) { }       /* a div containing an img */

:has() is the "parent of" selector, a CSS revolution!

Link-related

:link, :visited, :hover, :active, :focus-visible, :target

TL;DR

  • State pseudo-classes: hover, focus, active, visited.
  • Structural: first/last-child, nth-child, first-of-type.
  • Form: checked, disabled, invalid, placeholder-shown.
  • Modern: :not(), :is(), :has().
  • HUGE time-savers once you memorize them.