css - @mixin 通过使用参数选择一个特定的占位符
问题描述
我正在尝试在占位符内使用带有参数的mixin。这个想法是使用一行代码来选择类中的特定占位符。实际上,我不知道是否有另一种更好的方法可以做到这一点,也许是使用函数或其他方法。我正在学习 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);
}
谢谢你!
解决方案
目前,您的代码无法正常工作,因为您忘记添加%
before #{$val}
:
.box {
@extend %#{$val} !optional;
}
无论如何,将占位符选择器放在 mixin 中并不是一个好主意,因为每次调用 mixin 时,您都在创建新的选择器。这意味着例如,如果您添加:
.randomSelector {
@include box(box-one);
}
你会得到:
.wrap .box { ... }
.randomSelector .box { ... }
代替:
.randomSelector .box, .wrap .box { ... }
所以我建议你外部化%box-one
和%box-two
.
最后一件事,如果这两个类之间的唯一区别是background
属性,那么使用单个类重新组合公共属性可能会是更好的优化:
.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;
}
}
推荐阅读
- java - 设置瞬态对象变量而不在 Camunda 中序列化
- web - 有没有办法使用 traefik 将流量路由到非 dockerized web 应用程序
- android - CoroutineWorker 在重新打开应用程序后显示错误状态
- python - Get_loc 从 err 引发 KeyError(key)
- python - 为什么当我输入一些输入并按回车时,文本光标停留在最后一个输出行?- 这导致我在 CodeChef 上的回答是错误的
- java - 如何使用 pop() 反转堆栈并打印它?
- td-engine - TDengine 中 vgroup id 无效的原因是什么?
- stock - 指数化股票对数回报
- asp.net - ASP.Net 网站用户超时(由 StormInternet 托管)设置为 5 分钟 - 如何修复?
- ios - XCode:无法为旧项目编译 StoryBoard(ibtool 退出代码 10) - swift 3 和 pod