我构建了一个 mixin 来处理我的解决方案中的图标 sprite,它基本上循环遍历类名列表并设置相对于它在 sprite 中的索引的背景位置
@icon_size-small: 16;
@icon_size-medium: 24;
@icon_size-large: 32;
.commonIcons(@iconSize, @y: 1, @x: 0) {
@posY: (@iconSize * @y);
@posX: (@iconSize * @x);
background: url('images/icons/commonIcons@{iconSize}x@{iconSize}.png') -@posX + 0px -@posY + 0px no-repeat;
height: @iconSize + 0px;
width: @iconSize + 0px;
}
然后我像这样在另一个内部调用这个 mixin
.icons_list-small(@modifier, @x) {
.icon-clock { .commonIcons(@icon_size-small, 1, @x); }
.icon-checkmark { .commonIcons(@icon_size-small, 2, @x); }
.icon-stop { .commonIcons(@icon_size-small, 3, @x); }
etc
然后整个事情实际上是这样使用的
.small-button {
.icons_list-small(0);
}
所以背景位置是根据我使用的 .icons_list-xxx 计算的,我在 .small-button 中发送的参数决定显示哪个 y-index( Sprite 连续有 3 个变体)。
当在 .small-button 中作为子项生成时,这一切都很好,但我现在遇到了一个情况,我需要将列表生成为 sibling 选择器 到 .small-button (给我 .small-button.icon-clock { })
像这些例子一样实现它会给我解析错误,这是可以理解的:
.small-button.icons_list-small(0);
or
.small-button {
&.icons_list-small(0);
}
所以问题是:有人对我在这种情况下可以做什么有什么建议吗?
感谢大家的帮助!
编辑:我自己找到了一个修复方法,但如果有人有更优雅的解决方案,我会很高兴听到!
我所做的是像这样扩展 .icons_list-small mixin
.icons_list-small(@modifier, @x) {
@{modifier}.icon -clock { .commonIcons(@icon_size-small, 1, @x); }
然后这样调用
.icons_list-small(~".icon--inverted", 0);
最佳答案
一个解决方案是在你的 mixin 中使用 &
:
.icons_list-small(@x) {
&.icon-clock {
.commonIcons(@icon_size-small, 1, @x);
}
&.icon-checkmark {
.commonIcons(@icon_size-small, 2, @x);
}
&.icon-stop {
.commonIcons(@icon_size-small, 3, @x);
}
}
当你想获得以前的行为时,使用:
.small-button {
& * {
.icons_list-small(0);
}
}
哪个会产生
.small-button *.icon-clock {...}
...
相当于(在 CSS 中)
.small-button .icon-clock {...}
...
并且在没有 & *
的情况下使用它:
.small-button {
.icons_list-small(0);
}
将生成:
.small-button.icon-clock {...}
...
关于css - & 作为 LESS 中 mixin 的 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24059233/