RP McMurphy RP McMurphy - 6 months ago 12
CSS Question

Difference between & sign and no & sign in Sass?

This might be a very simple answer but I couldn't find it anywhere. Might be I missed a very basic CSS rule somehow.

Here is my Sass code:

h3 {
font-size: 20px;
margin-bottom: 10px;
&.some-selector {
font-size: 24px;
margin-bottom: 20px;
}
}


Output:

h3 {
font-size: 20px;
margin-bottom: 10px; }
h3.some-selector {
font-size: 24px;
margin-bottom: 20px; }


What difference does it make if I pull the '&' sign off? It just adds a space between 'h3' and '.some-selctor'. What's the meaning of this space between parent and child? Is there any difference actually?
Thanks in advance.

Answer

Using the & symbol will apply the rule "if" the current element has the accompanying class applied.

So in your example, the & rules (bigger font size and bottom margin) only apply IF the h3 also has the class .some-selector. eg:

<h3 class="some-selector"> My heading this is</h3>

If you removed the & sign, you are now defining a rule for its children (the space you noticed). So that would work with html such as:

<h3> My heading <span class="some-selector">this is</span></h3>

You can read more on this here: https://css-tricks.com/the-sass-ampersand/