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 Improve Your Workflow with Sass Extend the Properties of Selectors

Samantha Atkinson
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Samantha Atkinson
Front End Web Development Techdegree Graduate 40,307 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,725 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>