I'm using Sass (.scss) for my current project.
Following example:
HTML
<div class="container desc">
<div class="hello">
Hello World
</div>
</div>
SCSS
.container {
background:red;
color:white;
.hello {
padding-left:50px;
}
}
This works great.
Can I handle multiple classes while using nested styles.
In the sample above I'm talking about this:
CSS
.container.desc {
background:blue;
}
In this case all div.container
would normally be red
but div.container.desc
would be blue.
How can I nest this inside container
with Sass?
Best Answer
You can use the parent selector reference
&
, it will be replaced by the parent selector after compilation:For your example:
The
&
will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the&
.This notation is most often used to write pseudo-elements and -classes:
However, you can place the
&
at virtually any position you like*, so the following is possible too:However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.
*: No other characters than whitespaces are allowed in front of the
&
. So you cannot do a direct concatenation ofselector
+&
-#id&
would throw an error.