前端px转为rem的自适应解决方案

时间:2025-02-27 08:44:30

1.前端项目安装:npm install postcss-pxtorem --save-dev

2.在项目根目录下新增postcss.config.js文件,文件内容如下:

module.exports = {

  plugins: {

    'postcss-pxtorem': {

      rootValue: 16, // 1rem = 16px

      propList: ['*'], // 转换所有属性

      selectorBlackList: ['.no-rem'], // 忽略特定类名

    },

  },

};

3.动态设置根字体大小

在 src/main.js 中动态设置根元素的字体大小:

function setRem() {

  const baseSize = 16; // 基准大小

  const scale = document.documentElement.clientWidth / 1920; // 设计稿宽度为 1920px

  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'; // 限制最大缩放比例

}



setRem();

window.addEventListener('resize', setRem);

此种方案的样式需要写在css中,对于行内style中的样式不起作用