問題描述
寫一段代碼,我注意到我在一個地方寫了>:first-child
及以后的 >*:first-child
.兩個塊似乎都可以正常工作,但兩者之間有區(qū)別嗎?
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, but is there a difference between the two?
推薦答案
即使我們考慮性能,它們也是相同的.從規(guī)范我們可以閱讀
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.
所以寫>:first-child
應該和 > 的意思一樣.*:first-child
用于瀏覽器.
So writing > :first-child
should mean the same as > *:first-child
for the browser.
你也可以閱讀
注意:建議不要省略 * ,因為這樣可以減少例如 div :first-child
和 div 之間的潛在混淆:第一個孩子
.在這里,div *:first-child
更具可讀性.
Note: it is recommended that the * not be omitted, because it decreases the potential confusion between, for example,
div :first-child
anddiv: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.
在新規(guī)范中我們還可以閱讀:
除非元素是無特征的,否則通用選擇器的存在對元素是否匹配選擇器沒有影響.
Unless an element is featureless, the presence of a universal selector has no effect on whether the element matches the selector.
和
注意:在某些情況下,添加通用選擇器可以使選擇器更易于閱讀,即使它對匹配行為沒有影響.例如,div :first-child
和 div:first-child
乍一看有點難以區(qū)分,但將前者寫為 div *:first-child
讓區(qū)別顯而易見.
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
anddiv:first-child
are somewhat difficult to tell apart at a quick glance, but writing the former asdiv *:first-child
makes the difference obvious.
這篇關于> 之間是否存在功能差異?*:first-child 和 >:第一個孩子?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!