css-selectors - 在 LESS 中使用父选择器指定属性值?

标签 css-selectors less

是否可以在 LESS 中使用父选择器来指定父属性选择器的值?

我想要以下输出:

[some-attribute] {
    font-weight: normal;
}

[some-attribute~="bold"] {
    font-weight: bold;
}

给出这个(显然不正确的)例子:

[some-attribute] {
    font-weight: normal;

    &~="bold" {
        font-weight: bold;
    }
}

在 LESS 中可以实现这样的功能吗?

编辑:对于任何可能好奇的人,我确实尝试过这种可憎的做法:

[some-attribute {

    &] {
        font-weight: normal;
    }

    &~="bold"] {
        font-weight: bold;
    }
}

我很高兴它没有奏效。我可能受到了诱惑。

最佳答案

Disclaimer: This is strictly how not to over-complicate things but yeah it is still possible in a way using selector interpolation and mixins.

您可以编写如下所示的混入,将属性名称用作一个输入参数,将条件用作另一个输入参数。 condition 是一个可选参数,当它没有被提供时,mixin 认为它只是一个属性存在选择器。

必须附加的规则也作为输入传递。

.mixin-attrib-selector(@attr-name, @rule, @param:null){
    @sel-start: ~"[";
    @sel-end: ~"]";
    @{sel-start}@{attr-name}{
        & when(@param = null){
            &@{sel-end}{
                @rule();
            }
        }
        & when not (@param = null){
            &@{param}@{sel-end}{
                @rule();
            }
        }
    }
}

.mixin-attrib-selector(some-attribute, {
            font-weight: normal;
        });
.mixin-attrib-selector(some-attribute,{
            font-weight: bold;
        }, ~"~='bold'");

#output{
    .mixin-attrib-selector(some-attr, {
                font-weight: normal;
            });
    .mixin-attrib-selector(some-attr,{
                font-weight: italic;
            }, ~"~='italic'");
}

关于css-selectors - 在 LESS 中使用父选择器指定属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610566/

相关文章:

html - 具有三个 DIV 的 Flexbox 容器

css - gulp-sourcemap 文件扩展问题

javascript - 使用javascript在php代码中显示标签的值

html - 使用我的 CSS 选择器覆盖所有给定的 CSS 样式

css - 将 WinLess 与 Bootstrap 3.3.7 结合使用

javascript - 在 less 中访问空属性

node.js - 使用 grunt-contrib-less 编译更少的文件将不起作用

css - 使用字体和类的图标混合

css - 使用选择器的 child 之间的边界

css - 在 Less-CSS 中嵌套 >(大于)