萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 偽類單冒號 vs 偽元素雙冒號:語法規範與瀏覽器相容

CSS3 規範明確區分:單冒號 (:) 用於偽類,雙冒號 (::) 用於偽元素。

W3C 規範原文

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element. This :: notation is introduced to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility, 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.

對照表

瀏覽器支援策略

  • 現代瀏覽器 (Chrome, Firefox, Safari, Edge):**全面支援雙冒號**
  • IE 8-11:**僅支援單冒號** 偽元素 (:before 等)
  • 專案需支援 IE → 統一用單冒號或雙版本並存
  • 僅現代瀏覽器 → **全面雙冒號**,語意清晰、面向未來

實務建議

/* 兼容寫法:雙版本並存 */
::before, :before { content: ""; }
::after, :after { content: ""; }

/* 或使用 PostCSS autoprefixer 自動轉換 */
/* 輸入 ::before → 輸出 ::before, :before */

建議配合建置工具自動處理相容性,源碼統一使用雙冒號標準語法。

copyright © 萬盛學電腦網 all rights reserved
類型關鍵字CSS Level單冒號雙冒號建議
偽類:hover1✅❌單冒號
:focus2✅❌單冒號
:nth-child()3✅❌單冒號
:not()3✅❌單冒號
偽元素::before2✅ (兼容)✅雙冒號
::after2✅ (兼容)✅雙冒號
::first-line1✅ (兼容)✅雙冒號
::first-letter1✅ (兼容)✅雙冒號
::selection3❌✅必須雙冒號
::placeholder3❌✅必須雙冒號