Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS to Sass Refactoring with Sass Nesting Selectors

James Barrett
James Barrett
13,253 Points

I think I am having a blank moment here.. Where does .main come from?

Hi guys, we originally have this code snippet:

.main-heading {
 // do some stuff
}

.main-title {
// do some stuff
}

Then we create this new class which doesn't appear anywhere in the HTML structure: .main.

.main {
    .&-heading {
        // do some stuff
    }
    &-title {
        // do some stuff
    }
}

So my question is... What exactly is .main? And how does it get compiled to the original code snippet that we had before? Also, what would happen if we changed .main to say... .lead and then nested the rules below?

It seems simple... I'm just having an off moment here I think :P

Thanks, James.

1 Answer

andren
andren
28,558 Points

The & operator basically tells Sass to append the word following it to the selector that it is nested in. So &-heading with .main as it parent becomes .main-heading, &-title becomes .main-title. Therefore the Sass in your example will compile into this:

.main-heading {
}

.main-title {
}

Which is exactly what you started out with. So to answer more directly .main is indeed not a class assigned to any HTML element, but that doesn't matter. The purpose of it is just to act as a parent to the two nested selectors. And since you don't assign any properties to .main itself it won't be included as a rule in the compiled CSS.

For a simple example like this it might seem a bit overkill to structure your Sass like this, but imagine you had dozens of classes that started with .main. In that case this nesting technique would save you a lot of time typing that over and over again, which you would have to do with regular CSS.

And it results in all of the classes being very clearly grouped together, so that it's easy to see at a glance that they are related to each other when going though your Sass code.

James Barrett
James Barrett
13,253 Points

I see, thanks for the answer. However I feel having classes that aren't going to be used anywhere in the HTML structure would seem slightly confusing to the reader. Perhaps we could have separated anything with main into its own partial?

I know there are many ways to skin a cat. I am just trying to think of other ways to rewrite what Guil has done here

Thanks, James,