Skip to main content
Albero Academy

Selectors in Depth

Target exactly what you want — combinators, attribute selectors, pseudo-classes, pseudo-elements, and the modern :is / :where / :not.

Chapter 5CSS15 min readBeginner friendly
  • #CSS
  • #Selectors

Chapter 1 covered basic selectors. CSS has a far richer selection language that lets you target elements by relationship, attribute and state — often removing the need to add extra classes or JavaScript. Mastering selectors is what makes stylesheets concise.

Combinators

SelectorMatches
a bb anywhere inside a (descendant)
a > bb that is a direct child of a
a + bb immediately after a (adjacent sibling)
a ~ bany b after a (general sibling)
relationships
nav > li { } /* only top-level items, not nested */
h2 + p { } /* the paragraph right after an h2 */
label ~ input { } /* inputs that follow a label */

Attribute selectors

target by attribute
input[type="email"] { } /* exact match */
a[href^="https"] { } /* starts with */
a[href$=".pdf"] { } /* ends with */
[class*="btn"] { } /* contains */
[data-active] { } /* has the attribute at all */

Pseudo-classes

Pseudo-classes (single colon) match a state or position without needing a class:

state & position
a:hover, a:focus { text-decoration: underline; }
button:disabled { opacity: 0.5; }
input:checked { }
input:invalid { border-color: red; }
li:first-child { }
li:last-child { }
tr:nth-child(2n) { background: #f6f6f3; } /* zebra stripes */
li:nth-child(3) { } /* the third one */

Pseudo-elements

Pseudo-elements (double colon) style a part of an element, or insert generated content:

::before / ::after and more
.badge::before { content: "★ "; } /* insert content */
.card::after { content: ""; display: block; clear: both; }
p::first-line { font-weight: 600; }
::selection { background: #dbeafe; } /* highlighted text */
input::placeholder { color: #94a3b8; }

:is, :where & :not

These modern selectors keep long rules readable:

grouping helpers
/* Instead of h1 a, h2 a, h3 a { … } */
:is(h1, h2, h3) a { color: inherit; }
/* :where is the same but adds ZERO specificity — great for resets */
:where(ul, ol) { margin: 0; }
/* :not excludes */
button:not(.primary) { background: transparent; }

Practice

Style a nav so only direct child links get a border (>), zebra-stripe a table with :nth-child, add a "→" after external links with a[href^="http"]::after, and style all headings' links in one rule with :is().

Key takeaways

  1. 01Combinators target by relationship: descendant (a b), child (a > b), siblings (a + b, a ~ b).
  2. 02Attribute selectors match by attribute with ^= $= *= and presence [attr].
  3. 03Pseudo-classes (:hover, :checked, :nth-child, :first-child) match state and position.
  4. 04Pseudo-elements (::before/::after, ::placeholder, ::selection) style parts or insert content.
  5. 05:is()/:where() group selectors (:where adds no specificity); :not() excludes.