SASS 和数据属性选择和嵌套

标签 sass

我想将一些样式应用于具有数据属性product的元素,同时也应用于特定产品。

有办法做这样的事情吗?

// SASS
[data-product] {
  color: #000;
  &[="red"] {   // <- this line
    color: #f00;
  }
}

最佳答案

在 Sass 3.4 之前,这是根本不可能的。这里的破坏性功能是将当前选择器存储到变量中的能力以及分割字符串的能力(尽管后者可以通过 SassScript 函数创建)。

@mixin append-attr($x) {
    $sel: &;
    $collector: ();

    @for $i from 1 through length($sel) {
        $s: nth($sel, $i);
        $last: nth($s, -1);
        @if str-slice($last, -1) == "]" {
            // if is just the bare attribute with no value, $offset will be -1, otherwise it will be -2
            $offset: -1;
            $current-x: $x;

            @if str-slice($last, -2) == '"]' {
                // this attribute already has a value, so we need to adjust the offset
                $offset: -2;
            } @else {
                // no attribute value, so add the equals and quotes
                $current-x: '="' + $x + '"';
            }
            $last: str-slice($last, 1, $offset - 1) + $current-x + str-slice($last, $offset);
            $collector: append($collector, set-nth($s, -1, $last), comma);
        } @else {
            // following line will append $x to your non-attribute selector
            $collector: append($collector, selector-append($s, $x), comma);
            // the following line will not change your non-attribute selector at all
            //$collector: append($collector, $s, comma);
        }
    }

    @at-root #{$collector} {
        @content;
    }
}

用法:

[data-product] {
    color: white;

    @include append-attr("red") {
        color: red;

        @include append-attr('-green') {
            color: green;
        }
    }
}

[one], [two] {
    color: orange;

    @include append-attr('alpha') {
        color: yellow;
    }
}

[test], .test {
    @include append-attr('-one') {
        color: red;
    }
}

.bar input[min] {
    @include append-attr('5') {
        background: yellow;
    }
}

输出:

[data-product] {
  color: white;
}
[data-product="red"] {
  color: red;
}
[data-product="red-green"] {
  color: green;
}

[one], [two] {
  color: orange;
}
[one="alpha"], [two="alpha"] {
  color: yellow;
}

[test="-one"], .test-one {
  color: red;
}

.bar input[min="5"] {
  background: yellow;
}

相关:Modifying the middle of a selector in Sass (adding/removing classes, etc.)

关于SASS 和数据属性选择和嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25373991/

相关文章:

extjs4 - extjs 4主题如何使用全局变量创建自定义组件

css - 在 Ionic2 中设置 ionic 行高度大小

html - 将父 css 规则应用于子项

css - 如何在 Visual Studio 2012 中反射(reflect)运行时对 CSS 的更新?

css - for循环中的SASS CSS重复变量

html - Polymer 1.1 中的共享样式和外部样式表

sass - Webpack - 如何为 sass 加载器配置基本目录路径?

sass - Foundation 6不生成任何样式

css - 在 "quotes"中的 HTML 数据属性中使用 LESS 变量

sass - SCSS - 为什么扩展类会有这样的行为?