在回答“CSS/SCSS Adjacent sibling selector between certain types”这个问题时,如果父元素的第二个子元素和前面的兄弟元素是各种类型的元素,OP 希望对它进行样式化。
我提出了一个answer使用 matches()
选择器(尽管 Firefox 和 Webkit 浏览器——在撰写本文时——使用 :any()
伪类的供应商前缀实现) .
有点像 Internet Explorer 和 Edge 都无法实现任何版本的选择器的时代传统,无论是 :any()
还是 :matches()
,尽管这是一项实验性功能,但我不能为该决定或“失败”负责。
但是,为了兼容性,我想问一下:是否有一种方法可以使用 SASS 来形成适当的选择器来可靠地设置以下样式:
a::before {
content: 'link';
}
span::before {
content: 'span';
}
b::before {
content: 'b';
}
em::before {
content: 'em';
}
:-webkit-any(a, b, span) + :-webkit-any(a, b, span):nth-child(2) {
color: #f90;
}
:-moz-any(a, b, span) + :-moz-any(a, b, span):nth-child(2) {
color: #f90;
}
:matches(a, b, span) + :matches(a, b, span):nth-child(2) {
color: #f90;
}
<div>
<h2>The second element child of each of these following <div> elements should be styled</h2>
<div>
<span></span>
<a href="#"></a>
</div>
<div>
<a href="#"></a>
<span></span>
</div>
<div>
<a href="#"></a>
<span></span>
<span></span>
</div>
</div>
<div>
<h2>The second element child of each of these following <div> elements should <em>not</em> be styled</h2>
<div>
<a href="#"></a>
<em></em>
</div>
<div>
<em></em>
<a href="#"></a>
</div>
</div>
对于 SASS,我希望,或者至少想象,应该从以下形式扩展分组(虽然我不确定,因此这个问题是关于如何 模拟 :matches()
语法或 SASS 语法可能是什么):
:matches(a, b, span) + :matches(a, b, span):nth-child(2) {
color: #f90;
}
进入显式选择器,例如:
a + a:nth-child(2),
a + b:nth-child(2),
a + span:nth-child(2),
b + a:nth-child(2),
b + b:nth-child(2),
b + span:nth-child(2),
span + a:nth-child(2),
span + b:nth-child(2),
span + span:nth-child(2) {
color: #f90;
}
a::before {
content: 'link';
}
span::before {
content: 'span';
}
b::before {
content: 'b';
}
em::before {
content: 'em';
}
a + a:nth-child(2),
a + b:nth-child(2),
a + span:nth-child(2),
b + a:nth-child(2),
b + b:nth-child(2),
b + span:nth-child(2),
span + a:nth-child(2),
span + b:nth-child(2),
span + span:nth-child(2) {
color: #f90;
}
<div>
<h2>The second element child of each of these following <div> elements should be styled</h2>
<div>
<span></span>
<a href="#"></a>
</div>
<div>
<a href="#"></a>
<span></span>
</div>
<div>
<a href="#"></a>
<span></span>
<span></span>
</div>
</div>
<div>
<h2>The second element child of each of these following <div> elements should <em>not</em> be styled</h2>
<div>
<a href="#"></a>
<em></em>
</div>
<div>
<em></em>
<a href="#"></a>
</div>
</div>
引用资料:
最佳答案
这可能是一个解决方案,虽然不如使用 :matches
简洁,但也差不多了:
a, b, span {
& + a, & + b, & + span {
&:nth-child(2) {
color: #f90;
}
}
}
另一种方法是显式执行扩展循环:
$tags: a, b, span;
@each $a in $tags {
@each $b in $tags {
#{$a} + #{$b}:nth-child(2) {
color: #f90;
}
}
}
(也可以使用 mixin 编写,但这不会使它看起来更好......)
但实际上在这一点上,我会在上游工作以确保有一个类而不是那 3 个标签。
关于css - 如何使用 SASS 来模拟 :matches(a, b) + :matches(a, b) :nth-child(2)? 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445375/