h1 ~ span:not(h1 ~ span + span)
原文链接:h1 ~ span:not(h1 ~ span + span)
昨天知乎上有一位朋友提了这么一个问题,怎么使用相邻兄弟选择器“+”选中h1后面的这个`We are targeting this span element.`元素。
This is a span element.This is a span element.This is a span element.Heading
This is a p element
We are targeting this span element.This is a span element.This is a span element.This is a span element.This is a span element.
如果我们的目标span元素是紧跟着h1,那么h1 + span就搞定了,但是h1和目标span中间多了一个p元素,所以需要找其他方法。
h1 + span {background-color: orange;
}
接下来我们的第一直觉是可能想到h1 ~ span:nth-of-type(1),但是在h1前面还有其他span元素,所以这个方法也是不行的。
h1 ~ span:nth-of-type(1) {background-color: orange;
}
我的思路
首先找到h1后面的所有span,但需要排除这里面的第一个span。
h1 ~ span + span {background-color: orange;
}
然后利用反选伪类:not,找到所有不含第1步里面找到的span以外的其他所有span。这个选择器选中标题之前的所有span和标题之后的所有span中的第一个。
:not(h1 ~ span + span) {background-color: orange;
}
最后前面再用一个通用兄弟选择器“~”,那么就可以选中我们的一个目标span元素了。
h1 ~ :not(h1 ~ span + span) {background-color: orange;
}
还有一个思路
:not(h1 ~ span + span):is(h1 ~ span) {background-color: orange;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
