用rem來作響應式開發

咱們如今在切頁面佈局的使用經常使用的單位是px,這是一個絕對單位,移動端屏幕尺寸不少,通常設計圖都是按750px來設計,
rem(font size of the root element)是指相對於根元素的字體大小的單位。簡單的說它就是一個相對單位
em(font size of the element)是指相對於父元素的字體大小的單位。它們之間其實很類似,只不過一個計算的規則是依賴根元素一個是依賴父元素計算。
上面說過rem是經過根元素進行適配的,網頁中的根元素指的是html咱們經過設置html的字體大小就能夠控制rem的大小。
以下,經過改變根元素的單位就能夠適配不一樣寬度屏幕:
1 html{
2     font-size:62.5%; /* 10÷16=62.5% */
3 }
4 body{
5     font-size:1.2rem ; /* 12÷10=1.2 */
6 }
7 p{
8     font-size:1.4rem;
9 }

這裏我是經過設置以下的代碼來控制不一樣設備下的字體大小顯示使其達到自適應html

 

 1 html {
 2     font-size: 62.5%;
 3 }
 4 @media only screen and (min-width: 320px){
 5     html {
 6         font-size: 94%!important;
 7     }
 8 }
 9 @media only screen and (min-width: 375px){
10     html {
11         font-size: 109%!important;
12     }
13 }
14 @media only screen and (min-width: 414px){
15     html {
16         font-size: 125%!important;
17     }
18 }

也能夠使用js控制不一樣的設備寬度在根元素上設置不一樣的字體大小(1rem爲1/10屏幕寬度):web

 1 ;
 2 (function(win) {
 3     var doc = win.document;
 4     var docEl = doc.documentElement;
 5     var tid;
 6 
 7     function refreshRem() {
 8         var width = docEl.getBoundingClientRect().width;
 9         if (width > 540) { // 最大寬度
10             width = 540;
11         }
12         var rem = width / 10; // 將屏幕寬度分紅10份, 1份爲1rem
13         docEl.style.fontSize = rem + 'px';
14     }
15 
16     win.addEventListener('resize', function() {
17         clearTimeout(tid);
18         tid = setTimeout(refreshRem, 300);
19     }, false);
20     win.addEventListener('pageshow', function(e) {
21         if (e.persisted) {
22             clearTimeout(tid);
23             tid = setTimeout(refreshRem, 300);
24         }
25     }, false);
26 
27     refreshRem();
28 
29 })(window);

 

在使用一些框架的時候,能夠加入如下代碼,強制瀏覽器使用Webkit內核,國內不少的主流瀏覽器都是雙核瀏覽器:瀏覽器

1 <meta name="renderer" content="webkit">

 

 

 好好學習,每天向上,有錯歡迎指正!框架

相關文章
相關標籤/搜索