Skip to content

Instantly share code, notes, and snippets.

@chriseppstein
Created July 30, 2013 16:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseppstein/6114279 to your computer and use it in GitHub Desktop.
Save chriseppstein/6114279 to your computer and use it in GitHub Desktop.
Explanation of @extend with nested selectors.
%bordered {
.section & {
border: 1px solid #ccc;
}
}
.sidebar .quotation {
@extend %bordered;
}
.section .sidebar .quotation,
.sidebar .section .quotation {
border: 1px solid #ccc;
}

@andrewjamestait asked whether this is a bug in Sass. I have modified his question to use more concrete terms here because I find that the abstract names make it much harder to reason about.

The extend directive is simply a way of saying "Style elements matching this selector as if they matched the following simple selector".

As such, when .sidebar .quotation is extended, what we're really saying is, "if you see a quotation within a sidebar, please style it like it is a %bordered element". The extend directive is always addressing a single element but that element may have a document context, in this case, that context is "within a sidebar".

In our definition of %bordered, we're saying "Hey, there's this concept of things being bordered, but they only have a border if they are in a section."

Sass, when confronted with these two definitions cannot know how you will structure your documents. All Sass knows is that it needs to create selectors for an element that is both within a sidebar and within a section, and so Sass gives you two selectors with a permutation of all possible document orderings.

Astute readers will notice that there is a third possible document which is not present here: One where a section and a sidebar are the same element. So why doesn't Sass have .sidebar.section .quotation in the output when it is technically required? The answer is that we used to output that selector too, but the output became onerous and it was rarely an issue, and so as a heuristic we've decided to prune that selector to reduce the total output when working with nested selectors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment