简体   繁体   English

如何在CSS(使用属性)中选择不是另一个元素的后代的元素

[英]How select an element in CSS (using attribute) that is NOT a descendant of another element

After re-reading the CSS2.1 and CSS3 selector specs I suspect this is impossible, but you never know. 重新阅读CSS2.1和CSS3选择器规格后,我怀疑这是不可能的,但你永远不知道。

If I can select ap element, that is a decendent of other p element using the CSS decendant selector thus: 如果我可以选择ap元素,那么使用CSS后代选择器就是其他p元素的后代:

p p {};

Is there any way to negate the decendant selector, and still select on type, so I can select p elements, except those that are decendents of other p elements... 有没有办法否定后代选择器,仍然选择类型,所以我可以选择p元素,除了那些是其他p元素的后代...

p & ( p ! p ) {...};

ie I want to select elements of type p, but NOT if they decend from other elements of type p. 即我想选择p类型的元素,但如果它们偏离p类型的其他元素则不是。

BTW: I am using this in querySelector() and querySelectorAll(), where each one is selected by attributes not tag type, but I wanted to show the simplest example possible... 顺便说一下:我在querySelector()和querySelectorAll()中使用它,其中每个都是由属性而非标签类型选择的,但我想展示最简单的例子......

I tried this without success (syntax error!) 我尝试了这个没有成功(语法错误!)

p:not(p p) {......}
*:not(h1) p {
  ...
}

This is called the negation pseudo-class , and you can find more informations about it here . 这称为negation pseudo-class ,您可以在此处找到有关它的更多信息。

By the way, it is CSS3 so you can't use it with IE versions prior to 8. 顺便说一句,它是CSS3所以你不能在8之前的IE版本中使用它。

You suspect correctly, it is impossible. 你怀疑是正确的,这是不可能的。 :not(s) specifies that s must be a simple selector . :not(s)指定s必须是一个简单的选择器

The nearest thing you can do is to apply a style to all p and then override it for pp . 您可以做的最近的事情是将样式应用于所有p ,然后将其覆盖为pp

While the :not(...) selector is only CSS3, I usually use this for CSS2 compatibility: 虽然:not(...)选择器只是CSS3,但我通常使用它来兼容CSS2:

p { color: #abc; border: ... ; ... }
h1 > p { color: inherit; border: inherit; ... }

If your <p> s have a common ancestor, ie your html looks like this: 如果你的<p>有一个共同的祖先,即你的html看起来像这样:

<body>
    <p> ... </p>
    <p>
        <p> ... </p>
        <p> ... </p>
    </p>
</body>

you can use the "direct-child" selector: 你可以使用“直接子”选择器:

body > p { ... }

Or, of course, resetting all properties with something like: 或者,当然,重置所有属性,例如:

p p { color: inherit; background: inherit; ... }

would work too.. 会工作..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM