CSS: nesting selector (ampersand &)
Ampersand (&), the Nesting Selector
The ampersand & is called Nesting Selector.
when nested inside CURLY BRACKET {}, & represents the parent selector.
If used outside nesting, it represents the scoping root
:scope (usually selects the Root Element).
in nested CSS, you need the ampersand when you want to modify the parent selector, such as pseudo-class selector (:) and pseudo-element selector (::).
Example. pseudo-class
.card { &:hover { color: red; } } /* is equivalent to */ .card:hover { color: red; }
Example. Multiple nesting selector
.x { & > & > & { color: red; } } /* is equivalent to */ .x > .x > .x { color: red; }
Example. Relationship selectors
ul.xflow { li { /* ampersand UNNECESSARY */ & > a { display: block; } } } /* is equivalent to */ ul.xflow li > a { display: block; }
main { /* ampersand is UNNECESSARY in all cases below. */ /* direct child */ & > .content { color: red; } /* adjacent sibling */ & + .sidebar { color: red; } /* subsequent sibling */ & ~ .footer { color: red; } }
main { /* descendant (space). ampersand UNNECESSARY. */ & .title { color: red; } }
Example. Appended nesting selector (reverse parent/child)
🛑 WARNING: nesting syntax does not always mean the outer selector is parent.
The ampersand & symbol can be placed in different positions to create many many different relationships.
(see below)
/* Example. of reverse parent/child */ h2 { section > & { color: red; } } /* is equivalent to */ /* select the header title h2 only if it is direct child of section */ section > h2 { color: red; }
Examples
Multiple classes
/* Multiple classes */ .aa { &.bb { color: red; } } /* is equivalent to */ .aa.bb { color: red; }
Pseudo-elements
/* Pseudo-elements */ .aa { &::before { content: "★"; } } /* is equivalent to */ .aa::before { content: "★"; }
Attribute selectors
/* Attribute selectors */ .aa { &[data-accessed] { color: red; } } /* is equivalent to */ .aa[data-accessed] { color: red; }