CSS 百分比 margin & padding,css百分比margin

來源:互聯網
上載者:User

CSS 百分比 margin & padding,css百分比margin

前段時間我同事對於margin和padding應用百分比值似乎有些誤解,覺得可能是個普遍問題,所以覺得有必要拿出來單獨寫一下。

margin和padding都可以使用百分比值的,但有一點可能和通常的想法不同,就是margin-top | margin-bottom | padding-top | padding-bottom 的百分比值參照的不是容器的高度,而是寬度 。

引用標準(2.1)原來的表達:

 

The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

 

寬度參照寬度這點毫無疑問,但高度參照的也是寬度這點,可能就和通常的思路相左,因為畢竟height應用百分比參照的,依然是容器的高度。

關於為什麼標準要這麼定義,有幾種通常的解釋,就一併(個人)分析一下。由於padding和margin類似,下文就只以padding-top為例。

第一種說法是,padding-top如果以容器高度為參照,那麼子項目應用padding值將會繼續加高容器的高度,容器高度的變化又會反過來繼續影響子項目的padding-top,陷入一個無限迴圈。

對於不定高的容器來說情況確實如此,但對定高容器則並不成立,這點和height類似,這也是為什麼height的容器也必須確定好高度。也就是說,如果padding-top要參照容器高度,就必須和height一樣做兩種處理。

第二種說法則更為可靠, 為了保持padding(margin)四個值的一統一 。

padding(margin)的值無論引用何種計量,四個值都一直保持統一,難道單獨給百分比開特例?結合第一條的多情況處理,如果標準定義padding-top參照容器高度的話,恐怕要列出至少4條以上的例外說明——而這對無論誰,都沒有好處:)

事實上,垂直padding參照體是寬度這點也非常有用。雖然早期固化像素的設計中百分比值幾乎不應用在padding或者margin上,但隨著移動自適應的布局的需要,百分比也逐漸稀疏平常。比如配合background-sizing保持背景的比例,配合media query調整對應的間距,不一而足。這些應用都基於一個事實: 無論垂直還是水平,百分比值始終參考寬度 。

而寬度,實際上,正是自適應和現代web設計的靈魂。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.