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 Sass Basics (retired) Getting Started with Sass Advanced Nesting

Difference between & before and after selector

In the video, hampton showed us two way of advance nesting one is html.csscolumn & and other is &:hover . I am bit confused as when to use & before and when to & after. As if & after isn't already confusing.

2 Answers

Kevin Korte
Kevin Korte
28,149 Points

Just in case, I'm going to answer this the other way. When I read the question, I thought you were asking the same thing Moritz answered. But re-reading it, you may be asking what the & means, and how do you know where to put it. Very simply, when nesting selectors, the & is the placeholder for the selector that is being nested. So whether your & goes before or after your selector, depends on how you want the selector to be built.

So if I had very simple sass like this

 p {
    color: red;
    html.csscolumn & {
        margin: 30px;
    }
}

I would end up with this css

p {
    color: red;
}
html.csscolumn p {
    margin: 30px;
}

On the contrary, something like

 p {
    color: red;
    &:hover {
        margin: 30px;
    }
}

would generate

p {
    color: red;
}
p:hover {
    margin: 30px;
}

It's really quite simple when you break it down, & is just a placeholder for what it's nested in.

Moritz Lang
Moritz Lang
25,909 Points

Hi, &:after and &:before are basically the same thing. The only difference is where the content get's inserted. If you use &:before the content will be placed before the element, if you use &:after it will be placed after your element.