时间:2021-07-01 10:21:17 帮助过:7人阅读
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的详细内容,更多请关注Gxl网其它相关文章!