1. 程式人生 > >rem實現簡單的響應式佈局

rem實現簡單的響應式佈局

rem是什麼?

rem(font size of the root element)是指相對於根元素的字型大小的單位。簡單的說它就是一個相對單位。看到rem大家一定會想起em單位,em(font size of the element)是指相對於父元素的字型大小的單位。它們之間其實很相似,只不過一個計算的規則是依賴根元素一個是依賴父元素計算;

為什麼web app要使用rem?

這裡我特別強調web app,web page就不能使用rem嗎,其實也當然可以,不過出於相容性的考慮在web app下使用更加能突顯這個單位的價值和能力。

rem示例(程式碼):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文件</title>
<--!設定縮放!-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> <style>
.divs{ background-color: #e55058; width: 1rem; height: 1rem; margin: 0 auto; } </style> </head> <script>
//獲取螢幕當前尺寸並將其平分 window.onload = function(){ document.documentElement.style.fontSize = (document.documentElement.clientWidth
/750)*100+'px'; } </script> <body> <div style="width: 100%;height: 1rem;background-color: black"> <div class="divs" style="background-color: #0A9800;float: left"> </div> <div style="width: 5rem;height: 1rem;background-color: #0FC9B5;float: left"> </div> <div class="divs" style="float: right"> </div> </div> </body> </html>

實現效果圖:

  (1)pc端正常:

 (2)不同解析度移動端的顯示效果: