CSS中的html [lang =“en”]和html:lang(en)有什么区别?

CSS语言伪类允许我们为不同的语言指定不同的样式,如下所示:
html:lang(en) .foo { ... }

但是,这在IE7中不起作用,所以我一直在使用一个属性选择器:

html[lang="en"] .foo { ... }

他们似乎也做同样的事情,但有什么微妙的差异吗?如果没有,为什么CSS甚至有一个语言伪类,当属性选择器完全相同的事情?

解决方法

在HTML中,lan​​g()伪类和属性选择器将一个元素与相应的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.

06000

在您的示例中,以下选择器也将与.foo元素匹配:

.foo:lang(en)

但是如果没有自己的lang属性设置,以下选择器将不会:

.foo[lang="en"]
.foo[lang|="en"]

对于浏览器支持,从IE8开始支持lang()伪类,所以IE7真的是唯一通过在属性选择器上使用伪类无法支持的浏览器。

Selectors 4引入了:根据它们的方向性匹配元素的dir()伪类。因为方向性是与语言相关的属性,所以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,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]

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效