我正在尝试在占位符内使用带有参数的混合。 这个想法是使用一行代码来选择类中的特定占位符。 实际上,我不知道是否有另一种更好的方法来做到这一点,也许是一个功能或其他。 我正在学习 Sass,所以我正在尝试进行实验。
HTML
<div class='wrap'>
<div class='box'></div>
<div class='box'></div>
</div>
SCSS
// VAR
$size-xs: 30px;
$size-s: 50px;
$size-m: 70px;
$color-1: orange;
$color-2: rgb(34,139,86);
@mixin box($val) {
%box-one {
width: $size-s;
height: $size-s;
background: $color-1;
margin: auto;
border-radius: 6px;
}
%box-two {
width: $size-s;
height: $size-s;
background: $color-2;
margin: auto;
border-radius: 6px;
}
.box {
@extend #{$val} !optional;
}
}
.wrap {
width: 100%;
height: 100px;
background: #f5f5f5;
display: flex;
justify-content: space-between;
@include box(box-one);
}
谢谢!
最佳答案
目前,您的代码无法正常工作,因为您忘记在 #{$val}<
之前添加 %
:
.box {
@extend %#{$val} !optional;
}
无论如何,将占位符选择器放在混入中并不是一个好主意,因为每次调用混入时,您都在创建新的选择器。这意味着例如如果您添加:
.randomSelector {
@include box(box-one);
}
您将获得:
.wrap .box { ... }
.randomSelector .box { ... }
代替:
.randomSelector .box, .wrap .box { ... }
所以我建议您将 %box-one
和 %box-two
外部化。
最后一件事,如果这两个类之间的唯一区别是 background
属性,也许使用单个类重新组合公共(public)属性将是更好的优化:
.box {
width: $size-s;
height: $size-s;
margin: auto;
border-radius: 6px;
}
%box-one {
background: $color-1;
}
%box-two {
background: $color-2;
}
@mixin box($val) {
.box {
@extend %box-#{$val} !optional;
}
}
.wrap {
width: 100%;
height: 100px;
background: #f5f5f5;
display: flex;
justify-content: space-between;
@include box(one);
}
如果您有更多框样式,您甚至可以动态创建占位符:
$boxStyles: (
one: $color-1,
two: $color-2
);
@each $box, $style in $boxStyles {
%box-#{$box} {
background: $style;
}
}
关于css - @mixin 使用参数选择一个特定的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098824/