react项目如何使用rem
使用 rem 的配置方法
在 React 项目中配置 rem 单位适配移动端,可以通过以下方式实现:
安装 postcss-pxtorem 插件
npm install postcss-pxtorem --save-dev
配置 craco 覆盖 create-react-app 默认配置(如使用 CRA)

npm install @craco/craco --save
创建 craco.config.js 文件
module.exports = {
style: {
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 16,
propList: ['*']
})
]
}
}
}
动态计算 rem 基准值
在 public/index.html 的 head 中添加脚本

<script>
document.documentElement.style.fontSize =
Math.min(window.innerWidth, 750) / 750 * 100 + 'px'
</script>
或在 src/index.js 中添加 resize 事件监听
function setRem() {
const docEl = document.documentElement
const width = Math.min(docEl.clientWidth, 750)
docEl.style.fontSize = width / 7.5 + 'px'
}
window.addEventListener('resize', setRem)
setRem()
CSS 中使用 rem 单位
设置基础样式
body {
font-size: 16px; /* 1rem = 16px */
}
.container {
width: 10rem; /* 160px */
padding: 0.5rem; /* 8px */
}
设计稿尺寸转换
假设设计稿宽度为 750px,开发时可直接按设计稿尺寸书写
// postcss-pxtorem 配置
{
rootValue: 75,
unitPrecision: 5,
propList: ['*'],
selectorBlackList: [],
replace: true,
mediaQuery: false,
minPixelValue: 0
}
注意事项
使用 rem 布局时需确保所有尺寸单位统一为 rem
媒体查询中的尺寸也需要转换为 rem 单位
某些第三方组件可能需要单独处理样式覆盖
SVG 等矢量图形建议仍使用 px 单位保持清晰度




