最近面試問道rem的問題,按照原來的工做經驗解答,而後回來從網上搜索了一些關於rem的解釋和原理,發現跟本都不是本身想找的那種,就根據本身的理解寫了這一邊文章,以此記錄一下,方便本身查找。若有大神以爲個人理解不對,請您指出,萬分感謝。
如今開始說說我本身對rem的理解,其實說白了rem也就是在html裏面設置一個根字體,而後在用js動態獲取設備當前可視區的寬度,在跟設計圖作一個除法,最後得出px等於多少rem。javascript
舉個板栗:
一、我給頁面設置的根字體爲20px,假定設計圖給個人640尺寸,那我應該怎麼一個計算方式。
二、我給頁面設置的根字體爲20px,假定設計圖給個人750尺寸,那我應該怎麼一個計算方式。css
一、 20 * document.documentElement.clientWidth /(640/2)= 當前頁面根字體大小px。 二、 20 * document.documentElement.clientWidth /(750/2)= 當前頁面根字體大小px。
注:我通常簡化爲html
一、 20 * document.documentElement.clientWidth / 320 = 當前頁面根字體大小px。 二、 20 * document.documentElement.clientWidth / 375 = 當前頁面根字體大小px。
解釋一下:java
上面的理論說完,下面來講是實踐操做。如圖:web
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="stylesheet" href="index.css"> <script> document.documentElement.style.fontSize=20*document.documentElement.clientWidth/320+'px'; window.onresize=function(){ document.documentElement.style.fontSize=20*document.documentElement.clientWidth/320+'px'; }; </script> </head> <body> <header> <a href="javascrpit:;" class="menu"></a> <h1>demo</h1> <a href="javascript:;" class="pc"></a> </header> </body> </html>
*{ margin: 0; padding: 0; } a{ text-decoration: none; color: #fff; } header{ width:16rem; height:2.3rem; background: #262626; border-bottom: 0.1rem solid #4bccae; display: flex; justify-content: space-between; align-items: center; color: #fff; } .menu{ width:1.5rem; height:1.2rem; background: url(img/menu-bg.png) no-repeat; background-size:1.5rem 1.2rem; text-indent: -9999em; margin-left: 0.4rem; } h1{ font-size: 0.95rem; } .pc{ width:1.5rem; height:1.2rem; background: url(img/pc-bg.png) no-repeat; background-size:1.5rem 1.2rem; text-indent: -9999em; margin-right: 0.4rem; }
好了,記錄完畢。面試