CSS否定伪类:not()为父/祖先元素 [英] CSS negation pseudo-class :not() for parent/ancestor elements
问题描述
这让我吃惊:
HTML :
< div>< h1> Hello World!< / h1>< / div>
CSS:
*:not(div)h1 {color:#900; }
这不是读取,全选 h1
元素的祖先不是 div
元素...?因此,Hello World!
对于上面的标记,添加子组合器的工作原理:
< pre class =lang-css prettyprint-override>
*:not(div)> h1 {color:#900; }
但不影响 h1
元素,如果它不是 div
元素的子元素。例如:
< div>< article>< h1> Hello World!< / h1> article>< / div>
这是为什么我要指出 h1
元素作为 div
元素的子孙,而不是子元素。
不要读取,全选
h1
元素的祖先不是div
元素...?
它。但在典型的HTML文档中,每个 h1
至少有两个祖先不是 div
元素 - 这些祖先不是 body
和 html
。
这是尝试过滤祖先使用:not()
的问题:它只是不能可靠工作,特别是当 :not()
不被一些其他选择器限定,例如类型选择器或类选择器,例如 .foo:not(div)
。您将有一个更简单的时间,只需对所有 h1
元素应用样式,并覆盖 div h1
p>
在选择器4 中,:not()
已经增强,可以接受包含组合器的完整复杂选择器,包括后代组合器。这是否将在快速配置文件(因此CSS)中实现仍然需要测试和确认,但一旦实施,您将将能够使用它排除具有某些祖先的元素。由于选择器的工作原理,为了可靠地工作,必须对元素本身而不是祖先进行否定,因此语法看起来有点不同:
h1:not(div h1){color:#900; }
任何熟悉jQuery的人都会快速指出这个选择器今天在jQuery中工作。这是选择器3的:not()
和jQuery的:not()
,选择器4试图纠正。 >
This is driving me nuts:
HTML:
<div><h1>Hello World!</h1></div>
CSS:
*:not(div) h1 { color: #900; }
Doesn't this read, "Select all h1
elements that have an ancestor that is not a div
element...?" Thus, "Hello World!" should not be coloured red, yet it still is.
For the above markup, adding the child combinator works:
*:not(div) > h1 { color: #900; }
But doesn't affect the h1
element if it is not a child of a div
element. For example:
<div><article><h1>Hello World!</h1></article></div>
Which is why I'd like to indicate the h1
element as a descendant, not a child, of the div
element. Anyone?
Doesn't this read, "Select all
h1
elements that have an ancestor that is not adiv
element...?"
It does. But in a typical HTML document, every h1
has at least two ancestors that are not div
elements — and those ancestors are none other than body
and html
.
This is the problem with trying to filter ancestors using :not()
: it just doesn't work reliably, especially when the :not()
is not being qualified by some other selector such as a type selector or a class selector, e.g. .foo:not(div)
. You'll have a much easier time simply applying styles to all h1
elements and overriding them with div h1
.
In Selectors 4, :not()
has been enhanced to accept full complex selectors containing combinators, including the descendant combinator. Whether this will be implemented in the fast profile (and thus CSS) remains to be tested and confirmed, but once it is implemented, then you will be able to use it to exclude elements with certain ancestors. Due to how selectors work, the negation has to be done on the element itself and not the ancestor in order to work reliably, and therefore the syntax will look a little different:
h1:not(div h1) { color: #900; }
Anyone who's familiar with jQuery will quickly point out that this selector works in jQuery today. This is one of a number of disparities between Selector 3's :not()
and jQuery's :not()
, which Selectors 4 seeks to rectify.
这篇关于CSS否定伪类:not()为父/祖先元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!