One elaboration:
In that example, the &
's are unnecessary. This:
.className {
someselector { someattributes }
someselector { someattributes }
etc.
}
means the same thing. While they are harmless here, using them probably leads to confusion. Because there are circumstances where there are used, and there, they are necessary.
To understand that we must note that the most common selector combinator is easy to ignore: the descendant combinator, which is represented simply with a space. These two selectors have very different meanings:
div.my-class p /* Selector 1 */
div .my-class p /* Selector 2
^-------------- note the space */
The first one represents all P elements that are descendant from a DIV element with the class âmy-classâ. Example A: <div class="my-class"><article><p>Includes me</p></article></div>
The second one represents all P elements that are descendant from any element with the class âmy-classâ that are themselves descendant from a DIV element. Example B: <div><article class="my-class"><p>Includes me</p></article></div>
Note the the Example A is not captured by Selector 2, nor is Example B captured by Selector 1. So the spaces make a big difference.
When the CSS grammar was expanded to include these nested selectors, the obvious syntax was easily able to capture Selector 2, but not Selector 1. Thus we can rewrite Selector 2 like this:
div {
.my-class p {...rules...}
}
But there was no clear way to rewrite Selector 1. The &
is meant to fill those gaps. With it we can write
div {
&.my-class p {...rules...}
}
to mean the same thing as Selector 1. This is also useful for pseudo-classes such as :hover
. For instance, this:
a {
text-decoration: none;
color: blue;
&:hover {text-decoration: underline;}
&.warning {
color: red;
&:hover {background-color: #fcc;}
}
}
Is equivalent to
a {text-decoration: none; color: blue;}
a:hover {text-decoration: underline;}
a.warning {color: red;}
a.warning:hover {background-color: #fcc;}
There is much more information on MDN.