在前端开发中,经常遇到需要批量转换CSS单位的情况 🎨。比如将rem值转换为px,或者整合不同font-size基准的CSS文件。本文将介绍如何使用正则表达式快速完成这些转换。
常见场景:
- 📝 将rem值批量转换为px
- 🔄 整合不同font-size基准的CSS(如1rem=10px转换为1rem=16px)
- 🛠️ 第三方CSS库的单位统一
🔧 案例一:rem值批量修改为px
操作步骤
Chrome浏览器操作:
- 打开开发者工具(F12)
- 进入 Sources → Snippets → 新建代码段
- 粘贴代码并保存
- 右键运行,在控制台查看结果
中文界面操作: 源代码 → 代码段 → 新建代码段 → 保存 → 右键运行 → 控制台查看结果
代码示例
`
input,button,select{-webkit-appearance: none; -moz-appearance: none; outline: none;width:9.03rem;height:2.3rem;}
.test1 {box-shadow:0 0.6rem 1.6rem -0.7rem rgb(255, 85, 85);}
`.replace(/\d+(\.\d+)?rem/g, function(match) {
return parseFloat(match) + 'px'
})
运行结果
input,button,select{-webkit-appearance: none; -moz-appearance: none; outline: none;width:9.03px;height:2.3px;}
.test1 {box-shadow:0 0.6px 1.6px -0.7px rgb(255, 85, 85);}
🔄 案例二:不同font-size基准的rem转换
将1rem=10px的CSS转换为1rem=16px的CSS(转换比例:10/16 = 0.625)
代码示例
`
input,button,select{-webkit-appearance: none; -moz-appearance: none; outline: none;width:9.03rem;height:2.3rem;}
.test1 {box-shadow:0 0.6rem 1.6rem -0.7rem rgb(255, 85, 85);}
`
.replace(/\d+(\.\d+)?rem/g, function(match){
return (parseFloat(match) * 0.625).toFixed(2) + 'rem'
})
运行结果
input,button,select{-webkit-appearance: none; -moz-appearance: none; outline: none;width:5.64rem;height:1.44rem;}
.test1 {box-shadow:0 0.38rem 1.00rem -0.44rem rgb(255, 85, 85);}
🛠️ 在线工具
如果不想手动操作,也可以直接使用在线工具:在线CSS批量修改rem值工具
💡 提示: 使用正则表达式进行批量转换时,建议先在小范围测试,确认转换结果正确后再应用到整个CSS文件。