0

是否可以在不重复代码的情况下在 sass 中包含 css 规则?使用extend,我们正在扩展代码,但我不想要那个eiter。我想包含它,而不重复代码。

例如_

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;
}
4

1 回答 1

1

如果您使用扩展类(或使用与您在其他地方重复的类名不同的类名),您可以获得所需的输出:

%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;
}
于 2013-05-03T15:12:14.583 回答