Reputation: 7105
I have some rules nested inside each other, and I'd like to add another unrelated element to one of the rules. For example if I have
#element1{
display: block;
.sub-element1 {
background: yellow;
.sub-element2 {
color: red;
}
}
}
and then I'd like to add another element (#element2) to use same rules as .sub-element2, so compiled code would look like this:
#element1{
display:block
}
#element1 .sub-element1 {
background:yellow
}
#element1. sub-element1 .sub-element2, #element2 {
color: red;
}
Is it possible?
Upvotes: 1
Views: 684
Reputation: 9454
Use @extend
.
#element2 {
@extend .sub-element2
}
The output created by this will however also copy the selector chain, so this would be the output:
#element1. sub-element1 .sub-element2, #element2 {
color: red;
}
Perhaps that is what you want, but I can imagine it's not.
In this case you'll need to write an @extend only
selector. It works much like an @include
, except it generates the compact output you outline in your question. You could do it many ways, this is one of them:
%red {
color: red;
}
#element1{
display: block;
.sub-element1 {
background: yellow;
.sub-element2 {
@extend %red;
}
}
}
#element2 {
@extend %red;
}
Here's a link to it in the official docs.
Upvotes: 0
Reputation: 470
You could use a mixin. You can add rules to a mixin, then include the mixins where you want them:
@mixin redcolor {
color:red;
}
Then simply include this mixin in any selector:
.subelement2, #element2 {
@include redcolor;
}
More on mixins here: http://sass-lang.com/guide
Upvotes: 2