Consider the following code where nesting is done without the &
nesting selector.
.parent-rule {
/* parent rule properties */
.child-rule {
/* child rule properties */
}
}
When the browser parses the nested selectors, it automatically adds whitespace between the selectors to create a new CSS selector rule. The following code shows the equivalent non-nested rules:
.parent-rule {
/* parent rule style properties */
}
.parent-rule .child-rule {
/* style properties for .child-rule descendants for .parent-rule ancestors */
}
When the nested rule needs to be attached (with no whitespace) to the parent rule, such as when using a pseudo-class
or creating compound selectors, the &
nesting selector must be immediately prepended to achieve the desired effect.
Consider an example where we want to style an element, providing styles to be applied at all times, and also nesting some styles to be applied only on hover. If the &
nesting selector is not included, whitespace is added and we end up with a ruleset that applies the nested styles to any hovered descendant of the parent rule selector. This is, however, not what we want.
.parent-rule {
/* parent rule properties */
:hover {
/* child rule properties */
}
}
/* the browser parses the above nested rules as shown below */
.parent-rule {
/* parent rule properties */
}
.parent-rule *:hover {
/* child rule properties */
}
With the &
nesting selector added with no whitespace, the elements matched by the parent rule will be styled when hovered.
.parent-rule {
/* parent rule properties */
&:hover {
/* child rule properties */
}
}
/* the browser parses the above nested rules as shown below */
.parent-rule {
/* parent rule properties */
}
.parent-rule:hover {
/* child rule properties */
}