加入收藏 | 设为首页 | 会员中心 | 我要投稿 衡阳站长网 (https://www.0734zz.cn/)- 数据集成、设备管理、备份、数据加密、智能搜索!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

html – 与CSS级联:不是伪类

发布时间:2020-12-25 05:14:27 所属栏目:资源 来源:网络整理
导读:我很困惑为什么这个例子不起作用: CSS: p { color: red;}div:not(.exclude) p { color: green;} HTML: div div class="exclude" pI should be red/p /div div pI should be green/p /div/div 最终结果是 p是绿色的,但我原本预计第一个是红色的. Here’s a

我很困惑为什么这个例子不起作用:

CSS:

p {
  color: red;
}

div:not(.exclude) p {
  color: green;
}

HTML:

<div>
  <div class="exclude">
    <p>I should be red</p>
  </div>
  <div>
    <p>I should be green</p>
  </div>
</div>

最终结果是< p>是绿色的,但我原本预计第一个是红色的. Here’s a JSFiddle.

有趣的是,我找到了三种不同的方法来使它工作:

> Remove顶级< div>来自HTML
> Change顶级< div>到另一个元素(例如< section>)
> Add一个额外的div到第二个CSS选择器的开头(div div:not(.exclude)p)

另一个奇怪的方法来打破它:

>使用解决方案2作为基础,wrap另一个< div>围绕< section>

According to MDN:

This selector only applies to one element; you cannot use it to exclude all ancestors. For instance,body :not(table) a will still apply to links inside of a table,since <tr> will match with the :not() part of the selector.

这是有道理的,但我认为这不会发生在这里.由于< div class =“exclude”>之间没有任何内容和它的直接子< p>,它应该触发规则而不管它嵌套在里面.我错过了什么?如果有人能帮助我理解这一点,我真的很感激.

解决方法

Since there is nothing between <div class="exclude"> and its direct child <p>,it should trigger the rule regardless of what it is nested inside. What am I missing?

< p>是顶级< div>的后代.和< div class =“exclude”>.因此,虽然后者与选择器不匹配,但前者确实如此,因此您有匹配.无法匹配选择器的祖先更接近于< p>并且无关紧要.而不是那个.

解决方案1和2通过完全消除匹配来工作.

解决方案3在< p>的祖先中不存在其他< div>时起作用,因为这样您就可以按照确切的顺序将选择器限制为那些精确的条件.这意味着如果您从内部< div>交换了class属性对于外部的,它将不再匹配选择器,相反,如果您将类选择器从内部div交换到外部div,则选择器将与原始HTML结构不匹配(再次,假设没有其他< div> s存在于层次结构中).

包装另一个< div>围绕< section>只是让选择器再次被< div>匹配. <节>被忽略,与< div class =“exclude”>的方式大致相同.

也可以看看:

> CSS negation pseudo-class :not() for parent/ancestor elements
> Why doesn’t this CSS :not() declaration filter down?
> Is the CSS :not() selector supposed to work with distant descendants?

(编辑:衡阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读