Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS Sass Basics Improve Your Workflow with Sass Extend the Properties of Selectors

Samantha Atkinson
seal-mask
.a{fill-rule:evenodd;}techdegree
Samantha Atkinson
Front End Web Development Techdegree Student 30,218 Points

Ampersand VS @extend, do the same thing?

Have I understood the difference ampersand is used in nested selectors to target the parent element so the nested selector takes on the parents properties and values? Whereas @extend can be used in any rule?

2 Answers

Austin Whipple
Austin Whipple
29,686 Points

Hi Samantha,

Not quite. The ampersand is essentially a placeholder for the containing selector when nesting psuedo class properties, parallel class or ID selector properties, or using various combinators. For instance, instead of:

nav{}

nav.primary{}

nav.secondary{}

nav > ul{}

You could combine them:

nav {
   &.primary{}

   &.secondary{}

   & > ul{}
}

So it's not necessarily that the ampersand enables any sort of inheritance, but rather works more like a shorthand allowing you to group and nest style properties a bit. You can get pretty fancy with what you do with the ampersand. I highly recommend giving this CSS-Tricks article about it a read.

Meanwhile. @extend functions more like creating a comma-separated list of selectors and applying the same CSS rules to each of them. Instead of:

nav,
header,
footer {
     /*Some Styles*/
}

You'd instead do:

nav {
   /*Some Styles*/
}

header {
   @extend nav;
}

footer {
   @extend nav;
}

Both of these will output the same thing. Use cases vary, but I often find mixins way more useful. Speaking of, here's another relevant CSS-Tricks article for more information.

I had the same question. I believe one of the main differences with @extend is within the HTML markup. With @extend you only need .btn-info but with the & ampersand you need both .btn. and btn-info With @extend the markup would be something like this

<a class="btn-info" href="#">Learn more</a> 

Nesting with & ampersand would look like this

<a class="btn btn-info" href="#">Learn more</a>