Lab 01: Advanced Selectors

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Master CSS selectors beyond basics: attribute selectors, advanced pseudo-classes, specificity calculation, cascade layers, and logical properties. These skills unlock precise styling without class proliferation.


Step 1: Attribute Selectors

Attribute selectors target elements by their HTML attributes and values.

/* [attr]       — has attribute */
input[required] { border-color: red; }

/* [attr=val]   — exact match */
input[type="email"] { background: url(email-icon.svg) no-repeat right; }

/* [attr^=val]  — starts with */
a[href^="https"] { color: green; }    /* secure links */
a[href^="mailto"] { color: blue; }   /* email links */

/* [attr$=val]  — ends with */
a[href$=".pdf"]::after { content: " (PDF)"; }
a[href$=".zip"]::after { content: " (ZIP)"; }

/* [attr*=val]  — contains */
[class*="icon-"] { display: inline-block; width: 1em; height: 1em; }

/* [attr~=val]  — word in space-separated list */
[data-tags~="featured"] { border: 2px solid gold; }

/* [attr|=val]  — exact or prefix with hyphen (language codes) */
[lang|="en"] { font-family: "Georgia", serif; }

/* Case-insensitive flag */
input[type="TEXT" i] { outline: 2px solid blue; }

💡 Attribute selectors have the same specificity as class selectors (0,1,0).


Step 2: Structural Pseudo-Classes


Step 3: Specificity Calculation

Specificity is calculated as three numbers (A, B, C):

  • A = ID selectors (#id)

  • B = Class, attribute, and pseudo-class selectors

  • C = Element and pseudo-element selectors

Rules:

  1. Higher A always wins over any B or C

  2. !important overrides all specificity (use sparingly)

  3. Inline styles beat all selectors (treat as 1,0,0,0)

  4. :where() = zero specificity (0,0,0)

  5. :is() and :not() take specificity of their most specific argument


Step 4: Cascade Layers (@layer)

💡 @layer lets you manage CSS origin without fighting specificity wars. Libraries go in lower layers; your code wins.


Step 5: Logical Properties for Internationalization


Step 6: Combining Selectors Effectively


Step 7: Pseudo-Elements & Focus Management


Step 8: Capstone — Verified Specificity Calculator

📸 Verified Output:


Summary

Concept
Syntax
Specificity

Attribute starts-with

[href^="https"]

(0,1,0)

Attribute ends-with

[href$=".pdf"]

(0,1,0)

Attribute contains

[class*="icon"]

(0,1,0)

nth-child pattern

:nth-child(3n+1)

(0,1,0)

Not selector

:not(.disabled)

(0,1,0)

Is selector

:is(h1,h2,h3)

most specific arg

Where selector

:where(h1,h2,h3)

(0,0,0)

Has parent

:has(img)

(0,1,0)

Cascade layer

@layer name {}

layer order

Logical property

margin-inline-start

same as physical

Last updated