CSS單位rem
在W3C規范中是這樣描述rem
的:
font size of the root element.
移動端越來越多人使用rem,推薦淘寶開源框架lib-flexible
今天來介紹一下使用 預處理器轉換px單位到rem
首先是sass的
//定義一個變量和一個mixin $baseFontSize: 16;//默認基准font-size @mixin px2rem($name, $px){ #{$name}: $px / $baseFontSize * 1rem; } // 使用示例: .container { @include px2rem(height, 240); } // scss翻譯結果: .container { height: 3.2rem; }
再來一個less的
1 //定義一個變量和一個mixin 2 @baseFontSize: 75;//基於視覺稿橫屏尺寸/100得出的基准font-size 3 .px2rem(@name, @px){ 4 @{name}: @px / @baseFontSize * 1rem; 5 } 6 7 //使用示例: 8 .container { 9 .px2rem(height, 240); 10 } 11 12 //less翻譯結果: 13 .container { 14 height: 3.2rem; 15 }
最后是stylus的
//定義一個變量和一個mixin $baseFontSize = 16; //默認基准font-size px2rem(name, px){ {name}: px / $baseFontSize * 1rem; } // 使用示例: .container { px2rem('height', 240); } // stylus翻譯結果: .container { height: 3.2rem; }
最后,建議將mixin放入單獨文件夾下,例如webpack中的common
之后使用只需要在style中引入,以scss為例
@import "../common/scss/mixin.scss"; .all { @include px2rem(padding, 32); }
翻譯
如果,你是用Sublime Text3的同學,有福了,插件奉上cssrem