0
点赞
收藏
分享

微信扫一扫

h1 ~ span:not(h1 ~ span + span)

干自闭 2022-01-27 阅读 70
css前端

原文链接:h1 ~ span:not(h1 ~ span + span)

昨天知乎上有一位朋友提了这么一个问题,怎么使用相邻兄弟选择器“+”选中h1后面的这个`<span>We are targeting this span element.</span>`元素。

<div class="container">
  <span>This is a span element.</span>
  <span>This is a span element.</span>
  <span>This is a span element.</span>
  <h1>Heading</h1>
  <p>This is a p element</p>
  <span>We are targeting this span element.</span>
  <span>This is a span element.</span>
  <span>This is a span element.</span>
  <span>This is a span element.</span>
  <span>This is a span element.</span>
</div>

如果我们的目标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;
}
举报

相关推荐

0 条评论