gpt4 book ai didi

css - Less mixin 可以对某些元素类型应用特殊规则吗?

转载 作者:行者123 更新时间:2023-11-28 12:07:43 27 4
gpt4 key购买 nike

我有一个用于按钮样式的混合,我将它应用于按钮样式的 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 元素.

The support for :not is available in latest versions of all browsers and IE supports it from 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 来编写,因为否定选择器可以附加在末尾,而元素类型选择器不能。下面是编译后的 CSS 的演示。

.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)) 工作?

这个选择器不会工作(至少还没有)因为截至目前,negation :not selector accepts only simple selectors as arguments . :not(button)(外部否定的参数)不是一个简单的选择器。

关于css - Less mixin 可以对某些元素类型应用特殊规则吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com