问题
I am trying to find a way to include the parents styles within nested styles. In the code below, I want to include the width and box-sizing that are set on .random-div
in the two nested styles too, so that .random-div--large
would have width
, box-sizing
and padding
all set.
.random-div {
width: 100%;
box-sizing: border-box;
&--large {
padding: 65px 45px;
}
&--small {
padding: 25px 15px;
}
}
I've tried extending the parent class within the nested ones but that includes all of the other nested styles too. Is there any way to just include the parent styles?
回答1:
Create a placeholder and use that.
%random-div {
width: 100%;
box-sizing: border-box;
}
.random-div {
@extend %random-div;
&--large {
@extend %random-div;
padding: 65px 45px;
}
&--small {
@extend %random-div;
padding: 25px 15px;
}
}
回答2:
with your bem methodology your div should have both identifier and modifier and should look like this
<div class="random-div random-div--large"></div>
so it will get all three styles.
回答3:
You can use the @extend rule without using a placeholder, just reference the parent class you want to extend:
.random-div {
width: 100%;
box-sizing: border-box;
&--large {
@extend .random-div;
padding: 65px 45px;
}
&--small {
@extend .random-div;
padding: 25px 15px;
}
}
This will compile to:
.random-div, .random-div--small, .random-div--large {
width: 100%;
box-sizing: border-box;
}
.random-div--large {
padding: 65px 45px;
}
.random-div--small {
padding: 25px 15px;
}
Note you can't use the parent selector (&) with the @extend
rule, so this won't work:
.random-div {
width: 100%;
box-sizing: border-box;
&--large {
@extend &;
padding: 65px 45px;
}
&--small {
@extend &;
padding: 25px 15px;
}
}
来源:https://stackoverflow.com/questions/35992578/sass-include-parent-styles