作为一名前端开发,尤其是在做移动端适配时,rem是我们经常用到的单位,它的好处大家可以自行搜索,网上已经有很多了。
但是我们再将设计稿上的px转换成rem时,得手动的去计算,这是一个很耗时、费力的过程,有没有什么办法可以“解放”我们呢?(原谅我的懒~)
Sass、LESS以及PostCSS这样的处理器都可以处理。
@function px2em($px, $base-font-size: 16px) {
@if (unitless($px)) {
@warn "Assuming #{$px} to be in pixels, attempting to convert it into pixels for you";
@return px2em($px + 0px); // That may fail.
} @else if (unit($px) == em) {
@return $px;
}
@return ($px / $base-font-size) * 1em;
}@mixin px2rem($property,$px-values,$baseline-px:16px,$support-for-ie:false){
//Conver the baseline into rems
$baseline-rem: $baseline-px / 1rem * 1;
//Print the first line in pixel values
@if $support-for-ie {
#{$property}: $px-values;
}
//if there is only one (numeric) value, return the property/value line for it.
@if type-of($px-values) == "number"{
#{$property}: $px-values / $baseline-rem;
}
@else {
//Create an empty list that we can dump values into
$rem-values:();
@each $value in $px-values{
// If the value is zero or not a number, return it
@if $value == 0 or type-of($value) != "number"{
$rem-values: append($rem-values, $value / $baseline-rem);
}
}
// Return the property and its list of converted values
#{$property}: $rem-values;
}
}上面的方法,我们还得去额外学习sass这类的书写规则,也需要配置,虽然很简单,但是能不能更简单就更简单呢?
这是插件是flashlizi为sublime text编写的一个插件,用起来真的很方便!我们可以在GitHub上看到。
下面我介绍一下,如何配置:
立即学习“前端免费学习笔记(深入)”;
我们也可以修改默认配置:
打开cssrem-master文件夹下的cssrem.sublime-settings文件,进行修改
{
"px_to_rem": 40, //px转rem的单位比例,默认为40
"max_rem_fraction_length": 6, //px转rem的小数部分的最大长度。默认为6。
"available_file_types": [".css", ".less", ".sass",".html"]
//启用此插件的文件类型。默认为:[".css", ".less", ".sass"]
}实际测试:
新建一个.css文件:

11.png
按tab键,得到如下结果:

22.png
是不是很方便,快动手去尝试吧~
最后,附上 微网站—使用flexible.js实现移动端设备适配 。
以上就是css之px自动转rem的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号