Once I discovered you could use an ampersand selector in SASS to reference the parent, I haven’t gone back. I’m using it everywhere because it’s so useful. Here’s an example copied from an article – the article explains it better than I ever could.
h3
font-size: 20px
margin-bottom: 10px
.some-parent-selector &
font-size: 24px
margin-bottom: 20px
And here’s how the output CSS looks.
h3 {
font-size: 20px;
margin-bottom: 10px;
}
.some-parent-selector h3 {
font-size: 24px;
margin-bottom: 20px;
}
This is very useful! Especially when you want to keep css together by usage (I wrote about that here) so that you aren’t looking in multiple SASS files for information about every modification of a style.
Here’s how I used it today – I’ve got a class called “.copy” which is used for the content section of a page. There’s useful things in there like how the links and list items should look, because they’re a bit different to in the chrome (header & footer). But I wanted to create an aside section with different coloured text. Problem was, .aside p is the same specificity as .copy p, and I don’t want to start adding !important which could cause problems later on.
So I wanted to increase the specificity, but I didn’t want to add these styles for the aside inside the copy.scss – because that’s detached from the rest of the styles (which are in aside.scss). So I did this in my aside.scss:
.aside { .copy & p { color: #484848; } }
Notice it’s between the .copy and the p. It outputs like this:
.copy .vacancy-aside p { color: #484848; }