Parent Selector
The parent selector, &
, is a special selector invented by Sass that’s used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.
When a parent selector is used in an inner selector, it’s replaced with the corresponding outer selector. This happens instead of the normal nesting behavior.
⚠️ Heads up!
Because the parent selector could be replaced by a type selector like h1
,
it’s only allowed at the beginning of compound selectors where a type selector
would also be allowed. For example, span&
is not allowed.
We’re looking into loosening this restriction, though. If you’d like to help make that happen, check out this GitHub issue.
Adding SuffixesAdding Suffixes permalink
You can also use the parent selector to add extra suffixes to the outer selector. This is particularly useful when using a methodology like BEM that uses highly structured class names. As long as the outer selector ends with an alphanumeric name (like class, ID, and element selectors), you can use the parent selector to append additional text.
In SassScriptIn SassScript permalink
The parent selector can also be used within SassScript. It’s a special expression that returns the current parent selector in the same format used by selector functions: a comma-separated list (the selector list) that contains space-separated lists (the complex selectors) that contain unquoted strings (the compound selectors).
If the &
expression is used outside any style rules, it returns null
. Since
null
is falsey, this means you can easily use it to determine whether a
mixin is being called in a style rule or not.
Advanced NestingAdvanced Nesting permalink
You can use &
as a normal SassScript expression, which means you can pass it
to functions or include it in interpolation—even in other selectors! Using it in
combination with selector functions and the @at-root
rule allows you
to nest selectors in very powerful ways.
For example, suppose you want to write a selector that matches the outer
selector and an element selector. You could write a mixin like this one that
uses the selector.unify()
function to combine &
with a user’s selector.
⚠️ Heads up!
When Sass is nesting selectors, it doesn’t know what interpolation was used to
generate them. This means it will automatically add the outer selector to the
inner selector even if you used &
as a SassScript expression. That’s why
you need to explicitly use the @at-root
rule to tell Sass not to include
the outer selector.