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

Jacques Vincilione
Jacques Vincilione
17,292 Points

Ampersand and Sass

I'm much more familiar with LESS than I am with Sass, but I am using Sass in a project I'm currently working on. I'm trying to figure out what the significance of the Ampersand is in specific cases.

I understand why this is good to do (and it's pretty cool):

    .someClass{
        &.anotherClass{} 
     } 

But what is the point of this:

    .someClass{
        & .anotherClass{} 
     }

Wouldn't that be the exact same thing as:

    .someClass{
        .anotherClass{} 
     }

I've read a couple blogs that do that as well as the stylesheet I'm working on (someone else's work that I'm changing to a new layout - modularly)

Thanks for any explanations.

4 Answers

Hi Jacques,

The & in your second example would be redundant. The parent selector is already implied based on the nesting.

I would think that an experienced Sass developer would write it like your 3rd example.

Jacques Vincilione
Jacques Vincilione
17,292 Points

I'm glad to know I was thinking the right way. Thank you for helping to confirm that.

You're welcome.

You may want to check out the documentation for some examples of when you would want to use the & selector.

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

It's mainly useful for combining selectors and also to create a selector which uses an ancestor higher up the dom.

<div class="someClass"> <div class="anotherClass"></div> </div>

the class "anotherClass" is just a element in the class "someClass"

you are right, the last two are somehow the same

Example:

http://codepen.io/anon/pen/ivlbf

Sergi Beltran
Sergi Beltran
18,493 Points

When you're using ampersand you are writing the parent selector. Just that.

Jacques Vincilione
Jacques Vincilione
17,292 Points

You say, "somehow the same." Do you know any way they are different?

when you nest the elements you don't need a "&" just the name of the class

you can test it on the codepen I posted up there

Jacques Vincilione
Jacques Vincilione
17,292 Points

I understand that, and I [think I] understand what the ampersand does, but I'm just trying to make sure that it does not change it in any way.

Thanks.