跳到主要内容

移动端css方案适配

css方案​

媒体查询 + clamp + vw

  • 浏览器兼容性
    • clamp(): Chrome 79+, Safari 13.1+, Firefox 75+ (2020年支持)
    • calc() 所有现代浏览器
    • 因此用clamp和calc移动端基本无兼容问题
css
html.h5-layout {
font-size: clamp(13.6533px, calc(100vw / 23.4375), 32.768px);
}

@media (max-width: 320px) {
html.h5-layout {
font-size: 13.6533px;
}
}

@media (min-width: 320px) and (max-width: 768px) {
html.h5-layout {
font-size: calc(100vw / 23.4375);
}
}

@media (min-width: 768px) {
html.h5-layout {
font-size: 32.768px;
}
}

postcss-pxtorem配置​

  • 会将 px 自动转换为 rem

如nuxt中配置

  • 比如nuxt项目中,有pc和h5页面,只针对h5页面进行适配转换
js
postcss: {
plugins: {
'postcss-pxtorem': {
rootValue: 16,
propList: ['*'],
exclude: (file: string) => {
const f = file.replace(/\\/g, '/')
return (
!/pages\/h5\//.test(f)
&& !/layouts\/h5\//.test(f)
&& !/components\/h5\//.test(f)
&& !/components\/custom\/h5\//.test(f)
)
},
},
},
},

js动态计算​

  • 如果你需要在 JS 中动态计算 rem 单位(比如 canvas、动画等),可以动态设置转化
js
export function useRemCalc() {
const getCurrentRem = () => {
return parseFloat(getComputedStyle(document.documentElement).fontSize)
}

const px2rem = (px: number) => px / getCurrentRem()
const rem2px = (r: number) => r * getCurrentRem()

return { px2rem, rem2px }
}

taildwindcss单位转换问题​

  • 在taildwindcss写死的单位也是可以通过postcss-pxtorem来转换rem的