過去靠 Modernizr.js 做特性檢測,W3C 制定 @supports 原生 CSS 方案。現 Blink/WebKit/Gecko 全支援,僅 IE 不支援——反而方便針對 IE 差異化處理。
⚠️ 無法完全替代 JS:僅檢測 CSS 屬性,HTML5 API、WebP 等仍需 JS。
@supports (prop: value) { /* 樣式 */ }
@supports (display: flex) { div { display: flex; } }
not 否定邏輯@supports not (display: flex) { div { float: left; } /* 降級方案 */ }
支援 @supports 的瀏覽器通常支援現代屬性,但保留彈性應對私有前綴或未來變化。
/* OR:任一支援即套用 */
@supports (display: -webkit-flex) or (display: -moz-flex) or (display: flex) { ... }
/* AND:需同時支援 */
@supports (display: flex) and (-webkit-appearance: caret) { ... }
/* 混合:括號分組 */
@supports ((display: -webkit-flex) or (display: flex)) and (-webkit-appearance: caret) { ... }
/* 複雜否定 */
@supports ( not ((text-align-last: justify) or (-moz-text-align-last: justify)) ) { ... }
CSS.supports(propertyName, value); // 兩參數
CSS.supports(supportCondition); // 單字串條件
// 範例
CSS.supports("text-decoration-style", "blink");
CSS.supports("display", "flex");
CSS.supports("(transform-origin: 5% 5%)");
CSS.supports("(transform-style: preserve) or (-webkit-transform-style: preserve)");
回傳布林值,可用於動態載入樣式表或啟用功能。
替代 Modernizr 在 <html> 加類名的做法,直接在 CSS 內分支,減少 JS 依賴、避免閃爍。