Is there a functional difference between > *:first-child and > :first-child?

后端 未结 1 602
清歌不尽
清歌不尽 2020-12-04 00:56

Writing a block of code, I noticed that in one place I wrote > :first-child and later on > *:first-child. Both blocks appear to be functional

相关标签:
1条回答
  • 2020-12-04 01:25

    They are identical even if we consider performance. From the specification we can read

    If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

    So writing > :first-child should mean the same as > *:first-child for the browser.

    You can also read

    Note: it is recommended that the * not be omitted, because it decreases the potential confusion between, for example, div :first-child and div:first-child. Here, div *:first-child is more readable.

    So it's not only a matter of preference but it helps avoid confusion and make the code more readable.


    In the new sepcification we can also read:

    Unless an element is featureless, the presence of a universal selector has no effect on whether the element matches the selector.

    and

    Note: In some cases, adding a universal selector can make a selector easier to read, even though it has no effect on the matching behavior. For example, div :first-child and div:first-child are somewhat difficult to tell apart at a quick glance, but writing the former as div *:first-child makes the difference obvious.

    0 讨论(0)
提交回复
热议问题