CSS3 Selectors in Depth: Combinators, Attribute Selectors, Pseudo-Classes, Pseudo-Elements, Specificity and the Cascade
Combinators
| Selector | Meaning | Example |
|---|---|---|
A B | Any B inside A (descendant) | nav a |
A > B | B that is a direct child of A | ul > li |
A + B | B right after A (next sibling) | h2 + p |
A ~ B | Any B after A with the same parent | h2 ~ p |
Attribute Selectors
css
a[href^="https"] { color: green; } /* starts with */
a[href$=".pdf"] { font-weight: bold; } /* ends with */
a[href*="shop"] { text-decoration: underline; } /* contains */
input[type="email"] { border-color: #0b5fff; }
[disabled] { opacity: .5; }
Pseudo-Classes: States and Positions
css
a:hover { color: #0b5fff; }
a:focus-visible { outline: 3px solid #8ab4ff; }
button:active { transform: scale(.98); }
li:first-child { font-weight: bold; }
li:last-child { border-bottom: 0; }
tr:nth-child(even) { background: #f3f6fb; }
li:nth-child(3n) { color: crimson; } /* every 3rd */
p:not(.note) { margin-bottom: 1rem; }
input:checked + label { font-weight: bold; }
:hoverpointer is over it:focus-visiblefocused by keyboard:nth-child(2n)every second child:not(x)everything except x:checked,:disabled,:requiredform states
Pseudo-Elements: Parts of an Element
css
p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; }
.quote::before { content: "\201C"; color: #0b5fff; }
.quote::after { content: "\201D"; color: #0b5fff; }
::selection { background: #ffe08a; }
::before and ::after add generated content. They need the content property.
Specificity: Who Wins?
When two rules style the same property of the same element, the browser looks at specificity.
| Selector type | Strength |
|---|---|
| Inline style | Strongest |
Id selector #x | High |
Class, attribute, pseudo-class .x, [a], :hover | Medium |
Element, pseudo-element p, ::before | Low |
Universal * | None |
css
p { color: black; } /* low */
.intro { color: blue; } /* medium: wins over p */
p.intro { color: green; } /* medium + low: wins over .intro */
#top { color: red; } /* high: wins over classes */
The Cascade
- Importance:
!importantrules win (avoid using it) - Specificity: the stronger selector wins
- Order: if still equal, the later rule wins
Some properties like color and font-family are inherited by child elements. Others like border and margin are not.
Debug with DevTools Right click the element, choose Inspect and look at the Styles panel. Crossed out rules lost the cascade.
Practice
- Style only links to PDF files in a different color
- Make every second row of a list gray
- Add an arrow after external links with
::after
Conclusion
Combinators, attribute selectors, pseudo-classes and pseudo-elements let you target elements precisely. Specificity and order decide conflicts.
Quick Summary: Combinators; attribute selectors; pseudo-classes; pseudo-elements; specificity; cascade.

