在Less中使用@supports
@supports
是CSS的條件規則,用于檢測瀏覽器是否支持特定的CSS屬性或值。在Less中,你可以像在普通CSS中一樣使用@supports
,同時還能利用Less的特性來增強它。
基本用法
/* 檢測瀏覽器是否支持display: flex */
@supports (display: flex) {.container {display: flex;// 其他Flexbox相關樣式}
}
結合Less變量
// 定義變量
@my-property: grid;// 使用變量進行特性檢測
@supports (display: @my-property) {.grid-container {display: @my-property;grid-template-columns: repeat(3, 1fr);}
}
Less嵌套中的@supports
.container {display: block;@supports (display: grid) {display: grid;grid-gap: 20px;.item {// grid-specific item styles}}
}
AND/OR/NOT邏輯
// AND條件
@supports (display: flex) and (flex-wrap: wrap) {.flex-container { flex-wrap: wrap;}
}// OR條件
@supports (transform-style: preserve-3d) or (-webkit-transform-style: preserve-3d) {}// NOT條件
@supports not (display: grid) {}
Less mixin中使用@supports
.flexbox-mixin() {@supports (display: flex) {display: flex;&.column {flex-direction: column;}// mixin內容...}
}.container {.flexbox-mixin();
}
PostCSS注意事項
如果你使用PostCSS處理你的Less/CSS,確保你的PostCSS配置中包含postcss-preset-env
或類似的插件,以確保@supports
規則能在舊版瀏覽器中得到正確處理。
記住,@supports
是一個CSS特性查詢,不是Less特有的功能。Less編譯器會原樣保留這些規則(不會預處理它們),最終的樣式將由瀏覽器根據其支持情況來決定是否應用。
使用@supports
定義IOS安全區域
/** iPhone安全區域適配 */
.safe-area-adapt (@key: padding-bottom, @extra: 0px) {@safepadding: var(--safe-area-inset-bottom, '34px');@{key}: calc(@safepadding + @extra);
}
@supports (bottom: constant(safe-area-inset-bottom)) {padding-bottom: calc(5px + constant(safe-area-inset-bottom));
}
這段CSS代碼使用了@supports
規則來檢測瀏覽器是否支持constant(safe-area-inset-bottom)
特性,這是一種處理iPhone X及更新機型上"劉海屏"和底部Home指示條安全區域的方法。
代碼解釋:
@supports (padding-bottom: constant(safe-area-inset-bottom))
這是一個特性查詢(CSS Feature Query),檢查瀏覽器是否支持constant()
函數和safe-area-inset-bottom
變量
如果支持,則應用其中的樣式
padding-bottom: calc(8px + constant(safe-area-inset-bottom));
設置元素的底部內邊距為:8px + 設備提供的安全區域插入值
constant(safe-area-inset-bottom)
獲取設備底部的安全區域距離(在iPhone X及更新機型上,這會返回底部Home指示條的高度)
注意事項:
constant()
是舊版語法,現代瀏覽器使用env()
替代:
@supports (padding-bottom: env(safe-area-inset-bottom)) {padding-bottom: calc(8px + env(safe-area-inset-bottom));
}
最佳實踐是同時使用兩者,因為不同瀏覽器版本支持不同:
padding-bottom: calc(8px + env(safe-area-inset-bottom));
padding-bottom: calc(8px + constant(safe-area-inset-bottom)); /* 兼容舊版 */
這種技術常用于固定在底部的元素(如底部導航欄),確保它們不會被設備的圓角或Home指示條遮擋。
safe-area-inset-*
系列變量還包括:
safe-area-inset-top
safe-area-inset-right
safe-area-inset-left
這個解決方案特別適用于需要在所有設備上保持良好顯示效果的移動端網頁設計。