【问题标题】:The Sass ampersand and attribute selectorsSass & 和属性选择器
【发布时间】:2017-01-26 03:50:55
【问题描述】:

我想创建一个选择器将是属性选择器的 sass 文件。

当我使用类选择器时,在大多数情况下我会这样做

.parent {
    &-child {
    }
}

这给了我以下 css:.parent-child {}

我想用属性选择器达到同样的效果:

[data-parent] {
    &-child {
    }
}

我想成为的人:[data-parent-child] {}

有人知道如何做到这一点吗?谢谢。

【问题讨论】:

    标签: css sass compass-sass


    【解决方案1】:

    您可以使用此mixin 作为解决方法来获得所需的结果。

    @mixin child-attribute($child) {
      $string: inspect(&);
      $original: str-slice($string, 3, -4);
      @at-root #{ selector-replace(&, &, "[#{$original}#{$child}]" ) } {
        @content;
      }
    }
    

    代码只是做了以下事情

    1. $string 变量负责使用inspect 函数将父选择器转为字符串
    2. $original 变量负责获取$string 变量的文本 内容,即来自'([data-parent])' 的值'data-parent'
    3. selector-replace 函数然后用$original 变量和child 变量的串联替换父选择器

    当以下列方式使用时

    [data-parent] {
      @include child-attribute('-child') {
        color: green;
      }
    }
    

    css 输出

    [data-parent-child] {
      color: green;
    }
    

    根据你想要达到的目的,也可以这样使用

    [grandparent] {
      @include child-attribute('-parent') {
        color: white;
        @include child-attribute('-child') {
          color: blue;
        }
      }
    }
    

    生成以下css

    [grandparent-parent] {
      color: white;
    }
    
    [grandparent-parent-child] {
      color: blue;
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      您可以创建mixin,它将为具有数据属性的元素设置样式。

      文字:

      @mixin data($name) {
        [data-#{$name}] {
          @content;
        }
      }
      
      * {
        @include data('lol') {
          color: red;
        };
      }
      

      CSS 输出:

      * [data-lol] {
        color: red;
      }
      

      DEMO

      【讨论】:

      • 这不是解决方案,因为@include data('lol') 不能是父选择器,这错过了创建层次代码的所有目的。
      【解决方案3】:

      我会走一条稍微不同的路线,在包含data 属性的元素上添加class

      <div class="data-obj" data-parent="true"></div>

      <div class="data-obj" data-parent-child="true"></div>

      然后在你的 SASS 中做

      .data-obj {
          ...
      
          &[data-parent] { ... }
          &[data-parent-child] { ... }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-14
        • 2017-03-23
        • 2017-05-15
        • 2013-06-10
        • 1970-01-01
        相关资源
        最近更新 更多