The ampersand &
is the "parent selector" in Sass, and will append the rule that follows it to the containing parent scope. However, neither of the rules you have will work. The first...
.root{
:first-child{
color: green;
}
}
...would render to the CSS...
.root :first-child{
color: green;
}
...which would be invalid CSS, as the :first-child
pseudo-class expects to be attached to an actual CSS selector.
The second...
.root{
&:first-child{
color: green
}
}
...would render to CSS as...
.root:first-child{
color: green
}
...but that rule equates to "the first of any children with the class .root
should have color green," which is not what you desire.
For what you want--"to select the first child of the root container", you would want this CSS:
.root > *:first-child {
color: green;
}
<div class="root">
<p>some content</p>
<div>
<ul>
<li>some</li>
<li>other</li>
<li>content</li>
</ul>
</div>
</div>
...which equates to "the first direct descendent of any type in a container with class of .root
. This could be rewritten in sass a few different ways; with full nesting you could write it as
.root {
>* {
&:first-child {
color: green;
}
}
}
...but I would probably simplify it to...
.root {
>*:first-child {
color: green;
}
}