npm i postcss-px2rem -S
less编写直接写 px,例如直接写 32px,通过 postcss2rem直接转化为 rem
适配的三个问题
- 适配问题主要适配的是屏幕的三个要素
- 单位英寸像素数(Pixel Per Inch,PPI):现实世界的一英寸内像素数,决定了屏幕的显示质量
- 设备像素比率(Device Pixel Ratio,DPR):物理像素与逻辑像素(px)的对应关系
- 分辨率(Resolution):屏幕区域的宽高所占像素数
- 在当前环境下,分辨率适配可以使用 vw 单位解决,DPR 适配则需要用到 CSS 的 viewport 规则来控制缩放比例解决,而 PPI 主要影响的是文字,可以采用 media 规则来适配
postcss-plugin-px2rem
设计稿750尺寸,给的宽度是100px,在iphone6上其实是50px展示
rootValue是代码中,px转 rem的计算基准,因为rootValue中写的100,所以100px会被转换成1rem,
如果代码中是 200px,那么转换为 rem就是 2rem;
但在不同大小屏幕下,100px都会被转换成1rem,不同屏幕的 font-size不一样,
那么底层渲染出来的1 rem也不一样。就会有兼容问题。
并且我的设计搞的375px,那么我就想让375px等于屏幕的宽。
在.html文件设置 , 宽度按照iphone6屏幕尺寸 设置根节点的font-size
<script>const clientWidth = document.documentElement.clientWidth; // 375const fontSize = width / 7.5 // 375/7.5 = 50// 赋值之后,1rem 相当于50pxdocument.documentElement.style.fontSize = `${fontSize}px`;</script>

换算顺序关系: css写的px / rootValue * 根节点的px = 最终展示的px值,例如:
设计稿为 750px,一个盒子的高度为 50px,最终转换为rem的规则:
50px 书写的px / 100 rootValue * 50px 根节点的px =50/100 = 0.5 * 50
由于根节点设置了1rem = 50px; 最终页面展示为宽高都为 50px的盒子
不想被转换的 可以 以大写的PX 来绕过插件的编译 如
h1 {width: 100PX;height: 100PX;}
rem.js
// 基准字体大小const baseSize = 32// 设置 rem 函数function setRem() {// 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。const scale = document.documentElement.clientWidth / 750// 设置页面根节点字体大小document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'}// 初始化setRem()// 改变窗口大小时重新设置 remwindow.onresize = setRem;
public/index.html引入 rem.js
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"><link rel="icon" href="<%= BASE_URL %>favicon.ico"><title><%= htmlWebpackPlugin.options.title %></title><script src="./rem.js"></script></head><body><div id="app"></div><!-- built files will be auto injected --></body></html>
vue.config.js
vue3 vue.config.js配置 px2rem
const px2rem = require('postcss-px2rem')const postcss = px2rem({remUnit: 32})module.exports = {publicPath: './',css: {loaderOptions: {postcss: {plugins: [postcss]}}}}
组件中直接写 px,通过 px2rem会自动编译成 rem
<style lang="scss" scoped>.title { font-size: 32px }</style>
