CSS支援多種單位形式,如百分比、px、pt、rem等,百分比和px是常用的單位,隨著移動端和響應式的流行,rem、vh、vw也開始普遍使用,這些單位你可能未必知道,想瞭解?可以戳此文:CSS:7個你可能不認識的單位。
今天在SegmentFault社區碰到了兩個關於百分比計算的問題,一個是在translate中使用百分比的時候,是相對於哪個DOM元素的大小計算的;另外一個是在padding、margin等中使用百分比時,百分比又是怎麼轉為px的呢?
對於第一個,移動距離是根據自身元素的大小來計算的:
[The percentage] refer[s] to the size of the element’s box
具體參考:css3 translate in percent (自備梯子)
對於第二個,我認為percentage轉px應該是瀏覽器根據css規定來完成的,但是具體怎麼算呢?
Example 1: Margins
<div style="width: 20px">
<div id="temp1" style="margin-top: 50%">Test top</div>
<div id="temp2" style="margin-right: 25%">Test right</div>
<div id="temp3" style="margin-bottom: 75%">Test bottom</div>
<div id="temp4" style="margin-left: 100%">Test left</div>
</div>
得到的offset如下:
temp1.marginTop = 20px * 50% = 10px;
temp2.marginRight = 20px * 25% = 5px;
temp3.marginBottom = 20px * 75% = 15px;
temp4.marginLeft = 20px * 100% = 20px;
然後,我又測試了padding,原以為padding的值會根據應用了該屬性的相關元素來計算,但讓我驚訝的是,padding也是根據應用該屬性的父元素的寬來計算的,跟margin表現一致。(再插一句:當按百分比設定一個元素的寬度時,它是相對於父容器的寬度計算的,元素豎向的百分比設定也是相對於容器的寬度,而不是高度。)
但有一個坑,上面都是對於未定位元素。好奇的我又很好奇,對於非靜態定位元素的top, right, bottom, 和left的百分比值又怎麼計算呢?
Example 2: Positioned Elements
<div style="height: 100px; width: 50px">
<div id="temp1" style="position: relative; top: 50%">Test top</div>
<div id="temp2" style="position: relative; right: 25%">Test right</div>
<div id="temp3" style="position: relative; bottom: 75%">Test bottom</div>
<div id="temp4" style="position: relative; left: 100%">Test left</div>
</div>
得到的offset如下:
temp1.top = 100px * 50% = 50px;
temp2.right = 100px * 25% = 25px;
temp3.bottom = 100px * 75% = 75px;
temp4.left = 100px * 100% = 100px;
對於定位元素,這些值也是相對於父元素的,但與非定位元素不同的是,它們是相對於父元素的高而不是寬。
when the parent element does not have a height, then percentage values are processed as auto instead
雖然有點困惑,但只需要記住:對於margin和padding,百分比按照父元素的寬計算,對於定位元素,則按照父元素的高計算。