关于REM这个单位
关于REM的几篇文章
那么我们来说点他们没说的。 目前来说一般常用的REM是和媒体查询一起使用的。来处理手机端的宽度适应问题。一般手机的宽度在写了viewport(参见文章:http://adt.aicai.com/index.php/archives/179/)的情况下,都在320px-420px之间。如果我们想让宽度适应的更好。我们20px为基准取20px为分段单位写媒体查询。
html {font-size: 125%;}
@media (min-width: 320px) and (max-width: 340px) {
html {font-size: 125%;}
}
@media (min-width: 340px) and (max-width: 360px) {
html {font-size: 132.82%;}
}
@media (min-width: 360px) and (max-width: 380px) {
html {font-size: 140.62%;}
}
@media (min-width: 380px) and (max-width: 400px) {
html {font-size: 148.44%;}
}
@media (min-width: 400px) and (max-width: 420px) {
html {font-size: 156.26%;}
}
@media (min-width: 420px) and (max-width: 440px) {
html {font-size: 164.06%;}
}
@media (min-width:440px) and (max-width: 640px) {
html {font-size: 171.88%;}
}
或者更暴力一点用sass写一个1px为基准的媒体查询。
10px基准单位,生成的css文件大小4.95k,gzip大小1.1khttp://as3long.github.io/blog/demo/rem/media10px.css
@for $i from 320 to 420 {
@media (min-width:#{$i}px) {html {font-size: (62.5%*$i/320);}}
}
@each $size in 424,480,540,600,720,768,800,900,950,1200,1600{
@media (min-width:#{$size}px) {html {font-size: (62.5%*$size/320);}}
}
20px基准单位生成的css文件大小5.02k,gzip大小1.1khttp://as3long.github.io/blog/demo/rem/media20px.css
@for $i from 320 to 420 {
@media (min-width:#{$i}px) {html {font-size: (125%*$i/320);}}
}
@each $size in 424,480,540,600,720,768,800,900,950,1200,1600{
@media (min-width:#{$size}px) {html {font-size: (125%*$size/320);}}
}
针对640px设计稿的50px基准css文件http://as3long.github.io/blog/demo/rem/media50px.css 例如:640的设计稿的640px宽度对应的6.4rem; 640的设计稿的50px宽度对应的.5rem;
@for $i from 320 to 420 {
@media (min-width:#{$i}px) {html {font-size: (312.5%*$i/320);}}
}
@each $size in 424,480,540,600,720,768,800,900,950,1200,1600{
@media (min-width:#{$size}px) {html {font-size: (312.5%*$size/320);}}
}
还有一种办法是和js一起用的。
10px基准单位
(function(win,doc){
var h;
win.addEventListener('resize',function() {
clearTimeout(h);
h = setTimeout(setUnitA, 300);
}, false);
win.addEventListener('pageshow',function(e) {
if (e.persisted) {
clearTimeout(h);
h = setTimeout(setUnitA, 300);
}
}, false);
var setUnitA=function(){
doc.documentElement.style.fontSize = doc.documentElement.clientWidth/32 + 'px';
};
setUnitA();
})(window,document);
20px基准单位
(function(win,doc){
var h;
win.addEventListener('resize',function() {
clearTimeout(h);
h = setTimeout(setUnitA, 300);
}, false);
win.addEventListener('pageshow',function(e) {
if (e.persisted) {
clearTimeout(h);
h = setTimeout(setUnitA, 300);
}
}, false);
var setUnitA=function(){
doc.documentElement.style.fontSize = doc.documentElement.clientWidth/16 + 'px';
};
setUnitA();
})(window,document);
这段js的来源:https://github.com/amfe/lib.flexible/blob/master/flexible.js
为什么要用10px基准。原因是因为它比较好算,比如设计稿整体宽度是320px里面一个块是260px的宽度。换算成rem单位就是26rem。 如果设计稿宽度是640px里面一个块是320px的宽度。换算成rem就是16rem; 那为什么又有20px基准呢,20px不是就不好算了么。原因是chrome最小字体是12px.当你的基准单位是10px的时候,在chrome下不生效(ps:手机上10px通常是生效的。) 有两个方法解决这个问题。第一种就是以20px为基准。第二种设置chrome的最小字体为10px。设置方法浏览器输入chrome://settings/fonts,最小字号选项调整为10.