CSS中的百分比的使用方法

來源:互聯網
上載者:User


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,百分比按照父元素的寬計算,對於定位元素,則按照父元素的高計算。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.