1.安装依赖

npm install postcss-pxtorem

2.配置文件

根目录新建文件postcss.config.js

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-pxtorem': {
      // 转换的根元素的基准值
      // 正常去情下按照你的设计稿来
      // 1920 宽的设计稿, 1920 / 10 = 192
      // 750 宽的设计稿, 750 / 10 = 75
      // 370 宽的设计稿, 370 / 10 = 37.5
      rootValue: 16,// 结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem
      // 需要转换的CSS属性,*就是所有属性都要转换
      propList: ['*'],
    },
  },
};

3.配置尺寸变化函数

//src\pages\layout.tsx
//设置 rem 函数
function setRem() {
  // 1920 默认大小16px; 1920px = 120rem ;每个元素px基础上/16
  const screenWidth = 1920;
  const scale = screenWidth / 16;
  const htmlWidth =
    document.documentElement.clientWidth || document.body.clientWidth;
  // 得到html的Dom元素
  const htmlDom = document.getElementsByTagName("html")[0];
  // 设置根元素字体大小
  htmlDom.style.fontSize = htmlWidth / scale + "px";
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
  setRem();
};
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐