在媒体查询替代方案中使用SCSS @extend避免重复属性 [英] SCSS @extend inside media query alternatives to avoid duplicate properties
问题描述
在SCSS
中,可以使用@mixin
和@extend
重用代码.例如:
In SCSS
, you can use @mixin
and @extend
to reuse code. For example:
%even-row { background: pink; }
@mixin even-rows-mixin($columns) {
@for $i from 1 through $columns {
&:nth-child(#{2 * $columns}n + #{$i + $columns}) {
@extend %even-row;
}
}
}
li {
@include even-rows-mixin(8);
width: 12%;
}
会生成:
li:nth-child(16n + 9),
li:nth-child(16n + 10),
li:nth-child(16n + 11),
li:nth-child(16n + 12),
li:nth-child(16n + 13),
li:nth-child(16n + 14),
li:nth-child(16n + 15),
li:nth-child(16n + 16) {
background: pink;
}
li {
width: 12%;
}
但是,我想在媒体查询中使用mixin
,这是不可能的:
However, I'd like to use that mixin
inside a media query, which is not possible:
@media (max-width: X) {
li {
@include even-rows-mixin(8);
width: 12%;
}
}
@media (max-width: Y) {
li {
@include even-rows-mixin(4);
width: 16%;
}
}
这将引发错误:
You may not @extend an outer selector from within @media. You may only
@extend selectors within the same directive. From "@extend %even-row"
on line N.
我可以删除@extend
并内联mixin
中的属性:
I could just remove @extend
and inline the properties in the mixin
:
@mixin even-rows-mixin($columns) {
@for $i from 1 through $columns {
&:nth-child(#{2 * $columns}n + #{$i + $columns}) {
background: pink;
}
}
}
但这会生成重复的代码:
But that will generate duplicated code:
@nth-child(16n + 9) { background: pink; }
@nth-child(16n + 10) { background: pink; }
...
@nth-child(16n + 16) { background: pink; }
我想知道是否有更好的方式编写此代码而又不生成重复的属性,也不必手动编写所有可能的选择器,也许使用插值法或我不知道的其他功能.
I wonder if there's a better way to write this code without generating duplicated properties or having to write all the possible selectors manually, maybe using interpolation or some other feature I'm not aware of.
This question came to me after answering this other question: How to select even rows with list items, just as a reference if you want to take a look to the whole thing.
推荐答案
您可以使用整个选择器组构造一个选择器变量.
You can construct a selector variable with the entire selector group.
@mixin even-rows-mixin($columns, $rule) {
$selector : '';
@for $i from 1 through $columns {
$selector: $selector + $rule + '('+ #{2 * $columns}n + "+" + #{$i + $columns} + ') ,';
}
#{$selector} {
@content;
}
}
li {
width: 12%;
}
@include even-rows-mixin(8, 'li:nth-child') {
background-color: pink;
};
注意:由于某种原因,它在Codepen编辑器中不起作用.但是它可以和node-sass一起使用
Note: For some reason its not working in codepen editor. But it's working with node-sass
这篇关于在媒体查询替代方案中使用SCSS @extend避免重复属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!