REM

rem是什麼?

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

上面說過rem是通過根元素進行適配的,網頁中的根元素指的是html我們通過設置html的字體大小就可以控制rem的大小舉個例子。

html{
    font-size:20px;
}
.btn {
    width: 6rem;
    height: 3rem;
    line-height: 3rem;
    font-size: 1.2rem;
    display: inline-block;
    background: #06c;
    color: #fff;
    border-radius: .5rem;
    text-decoration: none;
    text-align: center;    
}
我們通過改變html中的font-size的大小來控制我們的dom元素的字體大小。

爲了適配不同分辨率的兼容,可以通過js來動態生成html裏的font-size的大小,我們也可以針對主流機型通過media query來設置。例如下面這邊代碼,不太瞭解media query可以學習下http://www.w3cplus.com/content/css3-media-queries

html{font-size: 20px;}
@media only screen and (min-width: 320px){
    html{font-size: 20px !important;}
}
@media only screen and (min-width: 350px){
    html{font-size: 22.5px !important;}
}
@media only screen and (min-width: 365px){
    html{font-size: 23px !important;}
}
@media only screen and (min-width: 375px){
    html{font-size: 23.5px !important;}
}
@media only screen and (min-width: 390px){
    html{font-size: 24.5px !important;}
}
@media only screen and (min-width: 400px){
    html{font-size: 25px !important;}
}
@media only screen and (min-width: 428px){
    html{font-size: 26.8px !important;}
}
@media only screen and (min-width: 432px){
    html{font-size: 27.4px !important;}
}
@media only screen and (min-width: 481px){
    html{font-size: 30px !important;}
}
@media only screen and (min-width: 569px){
    html{font-size: 35px !important;}
}
@media only screen and (min-width: 641px){
    html{font-size: 40px !important;}
}

當然在設置html中的font-size的時候,我們還可能會看到這樣的寫法,html {  font-size: 62.5% }。這主要是爲了方便em與px相互轉換,em的初始值爲1em=16px,顯然這樣的話,如1.2em則=19.2px,可是我們在設置的時候很少看見19.2px這樣表示的大小,也就是在用px表示大小時數值是不帶小數位的。當設置了body{font-size: 62.5%;}時,1em則=16px*62.5%=10px,1.2em則=12px,這是不是就簡單多了,準確多了呢~~。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章