CSS 语言伪类允许我们为不同的语言指定不同的样式,如下所示:
html:lang(en) .foo { ... }
但是,这在 IE7 中不起作用,所以我一直在使用属性选择器:
html[lang="en"] .foo { ... }
它们看起来做的是同一件事,但有什么细微的差别吗?如果不是,当属性选择器做完全相同的事情时,为什么 CSS 甚至有一个语言伪类?
最佳答案
在 HTML 中,:lang()
伪类和属性选择器都会匹配具有相应 lang
属性的元素。
不同之处在于,在针对 :lang()
伪类进行测试时,浏览器可能有其他方法来确定给定元素的语言,该伪类可能由文档语言和/或实现,而属性选择器将只检查元素是否有给定的属性,没有任何伴随的基于文档的语义。
例如,在 HTML 中,伪类还将匹配元素的任何没有不同 lang
的后代,具体取决于浏览器如何确定这些后代的语言。通常,如果未明确设置,后代将继承其祖先的语言属性。
这是 spec 的内容说:
The difference between
:lang(C)
and the ‘|=’ operator is that the ‘|=’ operator only performs a comparison against a given attribute on the element, while the:lang(C)
pseudo-class uses the UAs knowledge of the document's semantics to perform the comparison.In this HTML example, only the BODY matches
[lang|=fr]
(because it has a LANG attribute) but both the BODY and the P match:lang(fr)
(because both are in French). The P does not match the[lang|=fr]
because it does not have a LANG attribute.<body lang=fr> <p>Je suis français.</p> </body>
请注意“具有 LANG 属性”和“法语”的具体措辞。正如您想象的那样,这两个短语在英语中的含义截然不同。
在您的示例中,以下选择器也将匹配您的 .foo
元素:
.foo:lang(en)
但是下面的选择器不会,如果它没有自己的 lang
属性集:
.foo[lang="en"]
.foo[lang|="en"]
至于浏览器支持,:lang()
伪类从 IE8 开始被支持,所以 IE7 确实是唯一无法通过使用伪类来支持的浏览器属性选择器。
基于这种理解,您可以回答“我应该使用哪个”这个问题:您应该始终默认使用 :lang()
伪类,除非某些怪癖(或支持 IE7 的需要)需要使用属性选择器来解决。
选择器 4 不仅 brings enhanced functionality to the :lang()
pseudo-class (从而扩大了它与属性选择器之间的功能差距),而且 introduces the :dir()
pseudo-class用于根据方向性匹配元素。因为方向性是与语言相关的属性,dir
和 lang
属性在 HTML 中的作用相似,:dir()
和它的区别相应的属性选择器类似于 :lang()
及其相应的属性选择器之间的选择器——以至于下面引文的第一句实际上是逐字复制 描述 :lang()
部分中的同一段落:
The difference between :dir(C) and ''[dir=C]'' is that ''[dir=C]'' only performs a comparison against a given attribute on the element, while the :dir(C) pseudo-class uses the UAs knowledge of the document’s semantics to perform the comparison. For example, in HTML, the directionality of an element inherits so that a child without a dir attribute will have the same directionality as its closest ancestor with a valid dir attribute. As another example, in HTML, an element that matches ''[dir=auto]'' will match either :dir(ltr) or :dir(rtl) depending on the resolved directionality of the elements as determined by its contents. [HTML5]
关于css - html[lang ="en"] 和 html :lang(en) in CSS? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8916360/