@include和@extend之间的东西与sass
问题描述:
是否可以在sass中包含css规则而不重复代码? 随着扩展我们正在扩展的代码,但我不希望这个eiter。我想包括它,而不需要复制代码。@include和@extend之间的东西与sass
对于例如
SCSS:
.heading {
font-size: 16px;
font-family: my-cool-font;
}
.box {
background: red;
h1 {
@extend .heading;
color: white;
}
}
.my-other-box {
.heading {
color: black;
}
}
HTML
<div class="box">
<h1>My heading</h1>
</div>
<div class="my-other-box">
<h1 class="heading">My heading</h1>
</div>
CSS
.heading, .box h1 {
font-size: 16px;
font-family: my-cool-font;
}
.box {
background: red;
}
.box h1 {
color: white;
}
.my-other-box .heading,
.my-other-box .box h1,
.box .my-other-box h1 {
color: black;
}
所以最后两条规则是因为它的扩展(我理解它的好处)。 但是,如果我想都使用类,并扩展我不希望它扩展,只需包括它。但我不希望它重复的代码。
我想:
CSS
.heading, .box h1 {
font-size: 16px;
font-family: my-cool-font;
}
.box {
background: red;
}
.box h1 {
color: white;
}
.my-other-box .heading {
color: black;
}
答
如果使用扩展类(或使用从一个你在其他地方重复不同的类名),你可以得到输出你正在寻找:
%heading, .heading {
font-size: 16px;
font-family: my-cool-font;
}
.box {
background: red;
h1 {
@extend %heading;
color: white;
}
}
.my-other-box {
.heading {
color: black;
}
}
输出:
.box h1, .heading {
font-size: 16px;
font-family: my-cool-font;
}
.box {
background: red;
}
.box h1 {
color: white;
}
.my-other-box .heading {
color: black;
}