css之px自動轉rem

來源:互聯網
上載者:User
作為一名前端開發,尤其是在做移動端適配時,rem是我們經常用到的單位,它的好處大家可以自行搜尋,網上已經有很多了。
但是我們再將設計稿上的px轉換成rem時,得手動的去計算,這是一個很耗時、費力的過程,有沒有什麼辦法可以“解放”我們呢?(原諒我的懶~)

1.CSS處理器

Sass、LESS以及PostCSS這樣的處理器都可以處理。

Sass(使用Sass的函數、混合宏這些功能來實現):
@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;}
Sass(使用Sass的混合宏):
@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這類的書寫規則,也需要配置,雖然很簡單,但是能不能更簡單就更簡單呢?

2.CSSREM

這是外掛程式是flashlizi為sublime text編寫的一個外掛程式,用起來真的很方便!我們可以在GitHub上看到。

下面我介紹一下,如何配置:

2.1 我們可以在GitHub上下載所依賴的檔案;
2.2 開啟Sublime Text,進入packages目錄(Sublime Text -> Preferences -> Browse Packages);
2.3 將cssrem-master檔案夾放在上一步開啟的目錄中,重啟sublime text即可生效;
我們也可以修改預設配置:開啟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實現移動端裝置適配 。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.