英文:
SASS/SCSS Avoid duplicate properties including two mixins or extending two classes
问题
让我们假设我有两个可以使用@extend
(或者可以使用@include
)的类:
.small-text {
font-family: "MyFontFamily";
color: black;
line-height: 1rem;
font-size: 1rem;
}
.large-text {
font-family: "MyFontFamily";
color: black;
line-height: 1.4rem;
font-size: 1.4rem;
}
现在,在我的SCSS中,我可以这样做:
h1 {
@extend .large-text;
}
h3 {
@extend .small-text;
}
但是现在假设我想要使用一个类名,或者一个媒体查询,来有选择地从小文本切换到大文本:
h3 {
@extend .small-text;
&.big {
@extend .large-text;
}
}
我遇到的问题是编译后的CSS会变得非常重复,如下所示:
h3 {
font-family: "MyFontFamily";
color: black;
line-height: 1rem;
font-size: 1rem;
}
h3.big {
font-family: "MyFontFamily";
color: black;
line-height: 1.4rem;
font-size: 1.4rem;
}
有没有办法只在第二个选择器中包含从第一个选择器变化的属性?
英文:
Let's say that I have two classes that I can @extend
(or two mixins I can @include
) like so:
.small-text {
font-family: "MyFontFamily";
color: black;
line-height: 1rem;
font-size: 1rem;
}
.large-text {
font-family: "MyFontFamily";
color: black;
line-height: 1.4rem;
font-size: 1.4rem;
}
Now, all throughout my SCSS, I can do things like this:
h1 {
@extend .large-text;
}
h3 {
@extend .small-text;
}
But now let's say that I want to use a class name, or a media query, to selective change from small to large text:
h3 {
@extend .small-text;
&.big {
@extend .large-text;
}
}
The problem I'm having is the the compiled CSS is going to be really duplicative, like so:
h3 {
font-family: "MyFontFamily";
color: black;
line-height: 1rem;
font-size: 1rem;
}
h3.big {
font-family: "MyFontFamily";
color: black;
line-height: 1.4rem;
font-size: 1.4rem;
}
Is there any way to only include the changed properties in the second selector which changed from the first selector?
答案1
得分: 2
没有重复的部分,这正是您要求的。您应该做的是创建另一个类,small-text
和 large-text
都使用它,叫做 text
。
所以它会像这样:
.text {
font-family: "MyFontFamily";
color: black;
}
.small-text {
line-height: 1rem;
font-size: 1rem;
}
h3 {
@extend .text;
@extend .small-text;
&.big {
@extend .large-text;
}
}
因此,当您从 small
和 large
类中扩展时,它将仅包括 line-height
和 font-size
。
英文:
Nothing has duplicated, that is exactly what you asked for, what you should do instead is have a another class that both small-text
and large-text
both use called text
So it would be like this
.text {
font-family: "MyFontFamily";
color: black;
}
.small-text {
line-height: 1rem;
font-size: 1rem;
}
h3 {
@extend .text;
@extend .small-text;
&.big {
@extend .large-text;
}
}
So when you extend from the small
and large
classes it will only include the line-height
and font-size
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论