我有一个常用的组件,它的 scss 是这样的:
.component {
margin-right: 12px;
&.specified-use-case {
margin-right: 30px;
&:nth-child(odd) {
margin-right: 70px
}
}
}
现在我希望所有内容在移动 View 中都具有相同的样式
.component {
margin-right: 12px;
// some predefined mixin
@include viewport(mobile) {
margin-right: 0px;
margin-bottom: 14px;
}
&.specified-use-case {
margin-right: 30px;
&:nth-child(odd) {
margin-right: 70px
}
}
}
但这不能改变移动 View 中“specified-use-case”的样式。为了做到这一点,我必须
.component {
margin-right: 12px;
// some predefined mixin
@include viewport(mobile) {
margin-right: 0px;
margin-bottom: 14px;
}
&.specified-use-case {
margin-right: 30px;
@include viewport(mobile) {
margin-right: 0px;
margin-bottom: 14px;
}
&:nth-child(odd) {
margin-right: 70px
@include viewport(mobile) {
margin-right: 0px;
margin-bottom: 14px;
}
}
}
}
这对我来说似乎不对。有没有更好的方法来一次性定义移动 View css?
最佳答案
根据 CSS' specificity rules (尝试 this calculator )不幸的是,您需要重复一遍。您的 SCSS 解释器所做的只是将您编写的内容编译为标准 CSS,这看起来类似于:
.component {
margin-right:12px
}
@media (max-width:768px) {
.component {
margin-right:0px;
margin-bottom:14px
}
}
.component.specified-use-case {
margin-right:30px
}
@media (max-width:768px) {
.component.specified-use-case {
margin-right:0px;
margin-bottom:14px
}
}
.component.specified-use-case:nth-child(odd) {
margin-right:70px
}
@media (max-width:768px) {
.component.specified-use-case:nth-child(odd) {
margin-right:0px;
margin-bottom:14px
}
}
如您所见,您在声明每个类后立即使用 @media
规则集覆盖它。因为我强烈支持永远不要使用 !important
(因为你会打开一个潘多拉魔盒),缩短 SCSS 的唯一方法是:
.component {
margin-right: 12px;
// some predefined mixin
@include viewport(mobile) {
margin-right: 0px;
margin-bottom: 14px; // only need to define margin-bottom once, here.
}
&.specified-use-case {
margin-right: 30px;
@include viewport(mobile) {
margin-right: 0px;
//margin-bottom: 14px;, remove this
}
&:nth-child(odd) {
margin-right: 70px
@include viewport(mobile) {
margin-right: 0px;
//margin-bottom: 14px;, remove this
}
}
}
}
希望这对您有所帮助!
关于css - 如何在 SCSS 中使用 Mixin 覆盖引用父选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51622743/