The Sass ampersand and attribute selectors

半城伤御伤魂 提交于 2019-12-21 20:33:34

问题


I want to create a sass file that the selectors will be attribute selectors.

When I work with class selectors, in most of the cases I will do

.parent {
    &-child {
    }
}

which gives me the following css: .parent-child {}.

I want to achieve the same thing with attribute selectors:

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

which I want to become: [data-parent-child] {}

someone knows how to achieve this? thanks.


回答1:


You can use this mixin as a workaround to get the desired result.

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

The code simply does the following

  1. $string variable is responsible for turning the parent selector to a string using the inspect function
  2. $original variable is responsible for getting the text content of the $string variable i.e the value 'data-parent' from '([data-parent])'
  3. selector-replace function then replaces the parent selector with the concatenation of the $original variable and child variable

When used in the following ways

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

The css output

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

Depending on what you want to achieve, it can also be used like this

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

Which generates the following css

[grandparent-parent] {
  color: white;
}

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

Hope this helps you




回答2:


You can create mixin that will set styles for elements with data attribytes.

Scss:

@mixin data($name) {
  [data-#{$name}] {
    @content;
  }
}

* {
  @include data('lol') {
    color: red;
  };
}

Css output:

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

DEMO




回答3:


I would go down a slightly different route of having a class on your elements that contain the data attributes.

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

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

then in your SASS do

.data-obj {
    ...

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


来源:https://stackoverflow.com/questions/39556519/the-sass-ampersand-and-attribute-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!