某次專案中要用到 ::selection 這個偽元素,開發同事突然問我:CSS 裡一個冒號和兩個冒號到底差在哪?
這還真不失為一個好問題,或許不少前端同人也對此抱有疑惑。查了一些資料後,我確認了這兩個符號的區別,簡單來說就是:單冒號(:)用於 CSS3 偽類,雙冒號(::)用於 CSS3 偽元素。
W3C 在 CSS3 選擇器規範中有一段相關描述:
A pseudo-element is made of two colons (::) followed by the name of the pseudo-element. This :: notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in CSS level 3.
翻譯過來大意是:偽元素由雙冒號加上偽元素名稱組成。雙冒號是在當前規範中才引入的寫法,目的在於區分偽類與偽元素。不過為了相容既有的樣式表,瀏覽器仍必須接受舊有的單冒號寫法,像是 :first-line、:first-letter、:before、:after 等。
這樣一來,就能完整回答標題裡的問題了:對於 CSS2 之前就已存在的偽元素(例如 :before),單冒號與雙冒號的寫法 效果是完全一樣的。
所以,如果你的網站只需要相容 webkit、firefox、opera 等瀏覽器,建議偽元素採用雙冒號寫法;但要是不得不相容 IE,那麼保守起見,還是沿用 CSS2 的單冒號寫法比較安全。