@support 浏览器属性支持度判断
@support主要用于检测浏览器是否支持CSS的某个属性,可以用来做样式组的替补;但是@support对浏览器的版本有要求。
@support(prop:value){
/*自己的样式*/
}
// EG: 如果浏览器支持display:flex属性的话,那么div的样式就是display:flex
@supports (display: flex) { div { display: flex; }}
1.逻辑操作符:not的用法
//如果浏览器不支持display:flex属性的话,那么div的样式就是display:right
@supports not (display: flex) { div { float: right; }};
2.逻辑操作符:and的用法
//如果浏览器支持display:flex和box-shadow的属性,就执行里面自己的样式
@supports (display: flex) and ( box-shadow: 2px 2px 2px black ) {
/*自己的样式*/
}
3.逻辑操作符:or的用法
//如果浏览器支持其中一个就可以执行里面自己的样式
@supports (display: -webkit-flex) or (display: -moz-flex) or(display: flex) {
/*自己的样式 */
}
4.混用案例
//“or”和“and”混用,在@supports中“or”和“and”混用时,必须使用括号()来区分其优先级
@supports ((transition-property: color) or (animation-name: foo)) and (transform: rotate(10deg)) {
/*自己的样式 */
}
@supports (transition-property: color) or ((animation-name: foo) and (transform: rotate(10deg))) {
/*自己的样式 */
}
//“or”、“and” 和 “not” 混用
@supports (display: grid) and (not (transition-property: color) or (animation-name: foo)){
/*自己的样式 */
}
JS 结合supports 判断属性支持度
- 判断存不存在CSS
if (window.CSS && window.CSS.supports) {
}
//属性和值分开
let supportsGrid = CSS.supports("display", "grid");
//属性和值不分开
let supportsGrid = CSS.supports("(display: grid)");
- 判断是否支持具体的属性值或自定义的属性值
//判断是否支持fill-available(或fit-content)
@supports (height: fill-available) or (height: -webkit-fill-available) {
.child {
height: -webkit-fill-available;
height: fill-available;
}
}
.child {
width: 100px;
height: fill-available;
margin: 0 10px;
display: inline-block;
vertical-align: middle;
background-color: pink;
}
//判断是否支持自定义的属性
div {
color: red;
}
@supports (--css: variables) {
div {
--my-color: blue;
color: var(--my-color, "blue");
}
}
<div>
<h1>
浏览器支持变量则文字蓝色,不支持则文字红色
</h1>
</div>
选择器选择与设置meta标签
var isMobile = function isMobile() {
if (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1) {
return true;
}
return /android|ios|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent);
};
if (isMobile()) {
const metaEl = document.querySelector('meta[name="viewport"]');
metaEl?.setAttribute(
'content',
'width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'
);
}
rem、em、vh、px
- rem 是元素全部的长度都相对于根元素元素的字体大小;
- em 元素的字体大小是相对于父元素的字体大小;元素的width/height/padding/margin 用em 的话是相对于该元素的 font-size ;
- vw/vh 是视窗的宽度和高度;
- px 相对长度单位,是相对于显示器分辨率而言的;