Less mixin可以将特殊规则应用于某些元素类型吗



我有一个按钮样式的mixin,它适用于按钮样式的a标记和实际的button标记,但我使用的是垂直居中的flexbox,这在某些版本的Webkit中被破坏了。

例如,以下是我在Stylus中如何做到这一点,但我需要在Less:中完成同样的事情

.container {  
btn(width) {
display: flex;
flex-direction: column;
width: width;
height: 50px;
// How can I do this part, somehow, in Less?
../ button^[1..-1] {
display: inline-block;
}
}
.btn {
btn(100px);
}
}

以上是我在Stylus中的操作方式,但我希望找到另一种方法来绕过Less限制。我尝试附加到选择器,例如:not(:not(button)),但浏览器似乎不支持这一点。

Less(或任何预处理器)无法知道选择器表示的元素类型,因此在没有开发人员特别指示的情况下,他们无法生成此类规则。此外,Less不支持针对父选择器的特定部分并对其进行修改。因此,没有对所给出的Stylus代码进行直接转换。


话虽如此,有一些替代选项可以用来生成类似于Stylus代码的输出。

选项1:(使用CSS:not选择器)

我们可以使用CSS:not(否定)选择器将flexbox样式仅应用于不是button元素的.btn元素。

:not的支持在所有浏览器的最新版本中都可用,IE从9+开始支持它。

.container {  
.btn-mixin(@width) {
display: inline-block; /* default display is inline block */
width: @width;
height: 50px;
&:not(button){ /* override for elements that are not buttons */
display: flex;
flex-direction: column;
}
}
.btn {
.btn-mixin(100px);
}
}

这不能用flex的默认显示来编写,因为否定选择器可以附加在末尾,而元素类型选择器不能。

.container .btn {
display: inline-block;
width: 100px;
height: 50px;
}
.container .btn:not(button) {
display: flex;
flex-direction: column;
}
<div class="container">
<a href='#' class='btn'>Hello!</a>
<a href='#' class='btn'>we</a>
<a href='#' class='btn'>are</a>
<a href='#' class='btn'>some</a>
<a href='#' class='btn'>links</a>
</div>
<div class="container">
<button class='btn'>Hello!</button>
<button class='btn'>we</button>
<button class='btn'>are</button>
<button class='btn'>some</button>
<button class='btn'>buttons</button>
</div>


选项2:(使用较少参数化的混合)

这是不是我推荐的选项。在我看来,备选方案1更直接、更简单。我把这个加入到答案中只是为了表明条件行为可以在Less中实现。它使用guards功能来检查参数(@elType)的值,然后应用样式。

.container {  
.btn-mixin(@width; @elType: anchor) {
& when not (@elType = anchor){
display: inline-block;
}
& when (@elType = anchor){
display: flex;
flex-direction: column;
}
width: @width;
height: 50px;
}
.btn {
.btn-mixin(100px);
}
button.btn {
.btn-mixin(200px, button);
}
}

为什么:not(:not(button))不起作用

这个选择器不起作用(至少还没有),因为到目前为止,否定:not选择器只接受简单的选择器作为参数。:not(button)(它是外部否定的自变量)不是一个简单的选择器。

最新更新