CSS: nesting selector (ampersand &)
Ampersand (&), the Nesting Selector
The ampersand & is called Nesting Selector.
when used inside CSS nesting syntax, it represents the parent selector.
when used inside @scope, it represent the scope-root :scope.
If used outside nesting, it means :root.
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; }
CSS nesting syntax
CSS. Selectors
Selector types
Simple selectors
- CSS: type selector (tag name)
- CSS: universal selector (* any tag)
- CSS: class selector (.x)
- CSS: ID selector (#)
- CSS: attribute selector ([x])
Combinators
- CSS: descendant selector (space)
- CSS: child selector (>)
- CSS: adjacent sibling selector (+)
- CSS: subsequent sibling selector (~)
Selector list
Nesting syntax
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, last child, only child selectors
- CSS: nth-child selector
- CSS: nth-child arg of selector
- CSS: nth-of-type selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: :not negation selector
- CSS: :has descendant selector