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

原文链接: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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值