Sass&符和属性选择器 [英] The Sass ampersand and attribute selectors
本文介绍了Sass&符和属性选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个Sass文件,选择器将成为属性选择器。
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 {
}
}
这给了我以下CSS: .parent-child {}
。
which gives me the following css: .parent-child {}
.
我想通过属性选择器实现相同的目的:
I want to achieve the same thing with attribute selectors:
[data-parent] {
&-child {
}
}
我想成为: [数据-parent-child] {}
有人知道如何实现这一目标吗?
someone knows how to achieve this? thanks.
推荐答案
您可以使用此 mixin
作为解决方法预期的结果。
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;
}
}
代码只需执行以下操作
- $ string 变量负责使用
inspect $ c将父选择器转换为字符串$ c>函数
- $ original 变量负责获取
$ string
变量,即'([data-parent])'
'data-parent' > - 选择器替换函数,然后将父选择器替换为
$ original
变量的串联,并child
变量
- $string variable is responsible for turning the parent selector to a string using the
inspect
function - $original variable is responsible for getting the text content of the
$string
variable i.e the value'data-parent'
from'([data-parent])'
- selector-replace function then replaces the parent selector with the concatenation of the
$original
variable andchild
variable
按以下方式使用时
[data-parent] {
@include child-attribute('-child') {
color: green;
}
}
css输出
[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;
}
}
}
会生成以下CSS
[grandparent-parent] {
color: white;
}
[grandparent-parent-child] {
color: blue;
}
希望这对您有帮助
这篇关于Sass&符和属性选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文