介紹百分比懊蒸,em荣倾,rem
- 百分比的情況比較復雜:主要分5種情況
-
with
、padding
骑丸、margin
舌仍、right
、left
相對于父元素的width通危。 -
height
铸豁、top
、bottom
相對于父元素的height黄鳍。 -
font-size
相對于父元素的font-size推姻。 -
line-height
相對于自身的font-size。 -
border-radius
框沟、background-size
藏古、transform: translate()
增炭、transform-origin
、zoom
拧晕、clip-path
相對于自身寬/高
-
- em 表示自身字體尺寸的倍數(shù)(不是相對于父元素)
- rem
Equal to the computed value of font-size on the root element.
相當于根元素的計算值
適配方案
首先一定要加上
<meta name="viewport" content="width=device-width, initial-scale=1.0">
為了讓頁面可視寬度與手機可視寬度相同我們試著讓1rem=頁面寬度的一半
function init (){
var style = document.createElement('style')
var pageWidth = document.documentElement.clientWidth;
style.innerHTML = 'html{font-size :' + pageWidth/2 + 'px !important;}'
document.head.appendChild(style);
}
window.onresize=function(){
init()
}
window.onload=function(){
init()
}
這樣做雖然可以將rem做成類百分比隙姿。但是,當你遇到除不盡的尺寸的時候厂捞,寫起來會很麻煩输玷。而且,如果設(shè)計稿有定高的模塊的時候靡馁,你還得額外計算屏幕寬度的影響欲鹏。所以這樣做是很麻煩的,所以我們試著讓1rem與設(shè)計稿聯(lián)系起來臭墨,假設(shè)我們設(shè)計稿寬度是750赔嚎。那么我們可以這樣寫。
function init (designWidth){
var style = document.createElement('style')
var pageWidth = document.documentElement.clientWidth;
style.innerHTML = 'html{font-size :' + pageWidth/designWidth + 'px !important;}'
document.head.appendChild(style);
}
window.onresize=function(){
init(750)
}
window.onload=function(){
init(750)
}
這樣寫就能讓1rem等于設(shè)計稿的1px胧弛。但是還是會出現(xiàn)問題尤误,瀏覽器font-size
的最小單位是12px,假設(shè)你在iphone6下面開發(fā)结缚,html的font-size
為.5px
但是會被強制成12px损晤。這樣你做的就是無用功了。所以我們還需要一個rem2px
的變量來放大我們的font-size
//設(shè)計稿的尺寸750
//設(shè)置之后1rem=設(shè)計稿的40px
function init (desginWidth,rem2px){
var style = document.createElement('style')
var pageWidth = document.documentElement.clientWidth;
style.innerHTML = 'html{font-size :' + 40*pageWidth/desginWidth + 'px !important;}'
document.head.appendChild(style);
}
window.onload=function(){ init(750,40) }
我個人比較喜歡將rem2px設(shè)置成40红竭,有人會好奇尤勋,為什么不是20。還是因為最小font-size的限制茵宪,如果rem2px為20在ipad下面很容易突破12px的限制斥黑。
- 到目前為止還不算完,因為rem其實是一個計算值眉厨,在 html 的 fontSize 設(shè)置為 px 的情況下
1rem = 1 * (htmlFontSize / 16) * defaultFontSize
一般瀏覽器的默認值是16锌奴,但是如果用戶主動設(shè)置了defaultFontSize
就會出現(xiàn)偏差,這種情況我們可以用百分比來繞過去憾股。
function init (designWidth,rem2px){
var d = window.document.createElement('div');
d.style.width = '1rem';
d.style.display = "none";
var head = window.document.getElementsByTagName('head')[0];
head.appendChild(d);
var defaultFontSize = parseFloat(window.getComputedStyle(d, null).getPropertyValue('width'));
d.remove();
/*
到這里是為了獲得defaultFontSize系統(tǒng)默認字體
*/
document.documentElement.style.fontSize = window.innerWidth / designWidth * rem2px / defaultFontSize * 100 + '%';
}
這樣設(shè)置在defaultFontSize為16與我們第三步?jīng)]什么區(qū)別
Reference
除了上面方法
-
使用Flexible實現(xiàn)手淘H5頁面的終端適配
如何設(shè)置手淘的flexible
也給一個類似的方案
如何設(shè)置手淘的flexible