在回答问题“
CSS/SCSS Adjacent sibling selector between certain types”时,其中OP希望将父元素的第二个子元素设置为样式,并且前一个兄弟元素是各种类型的元素.
我使用matches()选择器提出了一个answer(尽管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>
参考文献:
> :any()
.
> :matches()
.
> Compatibility for :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个标签.