移动端rem布局和百分比栅格化布局

移动端的rem:

使用方法:

  • 设置html的font-size,根据浏览器分辨率缩放
      • 设置根元素font-size为100px这样好用的值,不要设为10px这样的;
      • 然后获取浏览器的分辨率,也就是视口宽度,p(比例尺)= 视口宽度/效果图宽度
      • 根元素font-size=100px*p
      • 然后来个resize去跟随浏览器大小变化
 1(function (win){
 7   var doc = win.document,
 8       html = doc.documentElement,
 9       option = html.getAttribute('data-use-rem');
10  
11   if( option === null ){
12     return;
13   }
14   
15   // defaut baseWidth : 640px;
16   var baseWidth = parseInt(option).toString() === 'NaN' ? 640 : parseInt(option);
17   var grids = baseWidth / 100;
18   var clientWidth = html.clientWidth || 320;
19 
20   // set rem first
21   html.style.fontSize = clientWidth / grids + 'px';
22   
23   // create testDom
24   var testDom = document.createElement('div');
25   var testDomWidth = 0;
26   var adjustRatio = 0;
27   testDom.style.cssText = 'height:0;1rem;';
28   doc.body.appendChild(testDom);
29 
30   var calcTestDom = function(){
31     testDomWidth = testDom.offsetWidth;
32     if( testDomWidth !== Math.round(clientWidth / grids) ){
33       adjustRatio = clientWidth/grids/testDomWidth;
34       var reCalcRem = clientWidth*adjustRatio / grids;
35       html.style.fontSize = reCalcRem + 'px';
36     } else{
37       doc.body.removeChild(testDom);
38     }
39   };
40 
41   // detect if rem calc is working directly
42   // if not , recalc and set the rem value
43   setTimeout(calcTestDom, 20);
44 
45   var reCalc = function(){
46     var newCW = html.clientWidth;
47     if ( newCW === clientWidth ){
48       return;
49     }
50     clientWidth = newCW;
51     html.style.fontSize = newCW*(adjustRatio?adjustRatio:1) / grids + 'px';
52     // if( testDom ) setTimeout(calcTestDom, 20);
53   };
54 
55   // Abort if browser does not support addEventListener
56   if (!doc.addEventListener){
57     return;
58   }
59 
60   var resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
61 
62   win.addEventListener(resizeEvt, reCalc, false);
63   // detect clientWidth is changed ?
64   doc.addEventListener('DOMContentLoaded', reCalc, false);
65   
66 })(window);

上面的是xiaojue写的一段代码,其中重要的一部分就是判断div的大小是否是精确的

说了rem布局,下面来说说百分比布局

百分比栅格化布局:

这里的栅格化布局方法和思路其实都很简单,就按照bootstrap的思路来,就是将一个容器,宽度一定或100%的,用一个分子去把这个容器分为很多份,bootstrap的方法是用百分比的方法来将这个容器分为n等份,这就是栅格化的思路,其实不难,就看你的思路是怎样的,实现起来也是不同。以后有机会会深入的学习一些栅格化布局的思想和优秀方法。

上面介绍了两种移动端布局方法,其实我们总结一下他们的优缺点,rem只能在移动端进行布局,然后等比例的缩放,在pc端还是用px这种惯用的方法去实现比较好,rem并不能实现响应式布局,这是重要的缺点,rem只在移动端起到一个比较好的作用,当然以后的发展会说不定,也可能还有人发明出厉害的设计方案。而百分比的布局,这种方式有一点是有很大问题的,他是无法做到定高的,这是为什么,因为百分比定高,有时候bug很明显,所以很多人用px定高,这样不同分辨率的手机会使得显示不一样。

原文地址:https://www.cnblogs.com/thecatshidog/p/4890557.html