Can the Universal selector * be replaced by :lang?

2019-06-04 03:20发布

问题:

The universal selector asterisk (*) is unique in that it matches a single element of any type.

So if I have different elements within a div and I want to select them all with one selector, I can either add a class to all the inner elements (something like .parent .class {}) or I can use the universal selector (.parent * {})

Then I saw the spec for the :lang pseudo element (particularly the end):

Note the difference between [lang|=xx] and :lang(xx). 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).

<body lang=fr>
  <p>Je suis Français.</p>
</body>

Which means that all elements within an element targeted by :lang selector are also targeted. (Wow!)

So let's say I wanted to add a border to all the elements within a div - instead of the selector div * {} I could theoretically use :lang

Here's a demo

As far as I can tell, the only difference is that the :lang selector selects the parent as well as all the children (and of course there's the technical difference the :lang has greater specificity)....however

if the :lang selector was applied in a semantic way that it included the whole document - with the lang attribute on the html element - I don't think that the above difference would matter.

So basically my question is:

Assuming that my html element has the attribute lang="en":

Can I replace code which uses the universal selector such like:

* { box-sizing: border-box; }

with:

:lang(en) {
  box-sizing: border-box;
}

The code seems to work (DEMO), and it seems to be semantic as well, but I'm wondering if there are certain reasons/cons to the above technique.

回答1:

Can the Universal selector * be replaced by :lang?

No, because you cannot write a selector using :lang() that is guaranteed to match all elements unless you assume all elements in the document will always be in the same language.1

If you're going to assume that all elements are in the same language, then using the :lang() pseudo is pretty pointless, since the whole point of that pseudo-class is to be able to distinguish parts of the document that differ in their content language.

Also note that the compound selector :lang(en) (consisting of just that one simple selector) is equivalent to *:lang(en). It is essentially the * selector with an additional qualification of a pseudo-class. You are not avoiding the use * by replacing it with :lang().


1 Selectors 4 allows a selector like :lang('*') to be written that matches elements in any language (which, again, is pointless if you don't care what language an element is in!), but this assumes the document even has content language semantics built into it. It is not clear if :lang() will work at all in a document lacking such semantics.