rem是設計響應式網頁的神器,由於rem單位是相對HTML元素的font-size屬性的,所以當使用rem做爲屬性單位時,當改變HTML元素的font-size,其餘使用rem做爲單位的元素也會跟着適配大小。那麼如何根據屏幕的大小製做一個響應式的網頁呢。css
這裏先說說用css媒體查詢,以下面所示,屏幕查詢能夠指定一個屏幕大小,當屏幕是你指定的大小時,它就會運行裏面的代碼,可是這種方法有一個缺點---它並不能控制更加精確的尺寸,因此咱們可使用vm來解決這個問題。html
<style> body,div{ margin:0; padding:0; } html{ font-size:12px; } @media screen and (min-width:320px){ html{ font-size:14px; } } @media screen and (min-width:640px){ html{ font-size:16px; } } @media screen and (min-width:1000px){ html{ font-size:18px; } } .box{ width:10rem; height:10rem; font-size:2rem; background-color:pink; } </style> <div class="box">rem</div>
視口單位能夠用來什麼,好比:佈局
這幾個單位是相對於視口的,也就是可視區域,總共分紅了100份。若是想讓一個字體的大小在指定的區間內變化,好比可視區域的大小在980px-320px時,讓字體的大小在14-20之間變化,能夠字體
14-(20-14)*(980-320)/(980-320)spa
<style> body,div{ margin:0; padding:0; } html{ font-size:20px; } @media screen and (max-width:980px){ html{ font-size:calc(14px+6*(100vm-320px)/660); } } .box{ width:10rem; height:10rem; font-size:2rem; background-color:pink; } </style> <div class="box">rem</div>
除了用這些基於視口的單位來作響應式,還能夠作一些其餘的事情。咱們知道,若是某個值能夠繼承,則百分比參照的是父元素計算的值。而當父元素不設置高度時,則是根據子元素高度來肯定的。因此,若是沒有直接設置寬度和高度,100%的設置是沒有做用的。若是用視口單位,就不會有這種狀況了,由於它是相對屏幕可視區的設計
.box{ width:100vw; height:100vh; background-color:pink; }
若是要實現水平垂直居中code
<style> body,div{ margin:0; padding;0; } .box{ width:100px; height:100px; margin-left:calc(50vw-50px); margin-top:calc(50vh-50px); background-color;pink; } </style> <div class="box">hello css</div>
用視口來實現網格佈局htm
<style> body,div{ margin:0; } .column-1{ float:left; width:100vw; } .column-2{ float:left; width:calc(100vw/2); } .column-3{ float:left; width:calc(100vw/3); } body>div{ overflow;hidden; } div>div{ height:35px; outline:1px solid #dedede; } .box-1 div{ background-color:red; } .box-2 div{ background-color:orange; } .box-3 div{ background-color:pink; } </style> <div class="box-1"> <div class="column-1"></div> </div> <div class="box-2"> <div class="column-2"></div> <div class="column-2"></div> </div> <div class="box-3"> <div class="column-3"></div> <div class="column-3"></div> <div class="column-3"></div> </div>
另外,當須要將圖片按照屏幕的比例顯示時,用視口單位也是不錯的選擇繼承
ch是一個相對於數字0的大小,好比定義了5ch的寬度,那麼就只能裝下5個0。實際上1ch=1個英文=1個數字,2ch=1箇中文。圖片
<style> body,div{ margin:0; padding:0; } .box{ width:5ch; background-color:grey; } </style> <div class="box"> 000000 </div>
若是項目須要限制輸入個數,可使用下面代碼
<style> body,div{ margin:0; padding:0; } h1{ width:18ch; overflow: hidden;//超出隱藏 white-space: nowrap;//防止換行 text-overflow: ellipsis;//省略號 font-size: 50px; background-color: deeppink; } </style> <h1> 標題被限制輸入了,超出隱藏哦。 </h1>