CSS盒子模型知識總結

來源:互聯網
上載者:User
本章內容:

知識點一:

盒子模型:Box Model,由有內容(element content)、填充(padding)、邊框(border)、邊界(margin)這四個組成部分,這四個部分都包含有top/right/bottom/left四個組成部分。

從w3school上下載的圖片,以圖來看看盒子模型的四個組成部分

說明:圖中元素框的最內部分是實際的內容(element);直接包圍內容的是內邊距(padding),內邊距呈現了元素的背景(background);內邊距的邊緣是邊框(border);邊框以外是外邊距(margin),外邊距預設是透明的,因此不會遮擋其後的任 何元素(其實元素的margin就是其所在父元素的padding)。

一個元素放在頁面上究竟需要多大尺寸時,把已經聲明內邊距,邊框,外邊距值統統與內容地區加上。當然,如果一個元素沒有內邊距,邊框,外邊距的話,也就是它的尺寸僅僅是由它的內容來決定。先忽略外邊距的疊加效果,計算公式如下:

Total width = left margin + left border + left padding + width + right padding + right border + right margin

Total height = top margin + top border + top padding + height + bottom padding + bottom border + bottom margin

以其中一個例子為例:

引入代碼:

<p style="width: 500px;"> <p style="margin: 10px; border: 5px solid blue; padding: 10px; ">   網上很多設定的方式,目前以二進位的方式來講解(ID CLASS ELEMENT)   網上很多設定的方式,目前以二進位的方式來講解(ID CLASS ELEMENT)   網上很多設定的方式,目前以二進位的方式來講解(ID CLASS ELEMENT) </p></p>

以上的元素總共被計算出來的的尺寸是:

Total width = 10 + 5 + 10 + 450+ 10 + 5 + 10 = 500px

Total height = 10 + 5 + 10 + 72+ 10 + 5 + 10 = 122px

知識點二:

對盒子模型有了初步認識後,我們考慮到這幾個情境:

1.相對定位或者無定位的情況(預設為position為static)

引入代碼:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">.box {  background:black;  color:White;  height:100px;  padding:10px;  border:20px solid Red;  margin:30px;}</style></head><body>  <h2>Static or Relative Box</h2>  <p class="box">不設定任何position屬性及寬度</p></body></html>

則塊的寬度是延伸自動填滿滿它的父元素的寬度地區

2.浮動float元素和絕對位置元素(具有包裹性,通過設定display: table;也能實現包裹性效果,可以自己設定看看效果)

引入代碼:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">.box {  background:black;  color:White;  height:100px;  padding:10px;  border:20px solid Red;  margin:30px;  position: absolute;}</style></head><body>  <h2>Absolute or Float Box</h2>  <p class="box">不設定任何position屬性及寬度</p></body></html>

3.特殊性:設定p的樣式為box-sizing: border-box;

引入代碼:

<p style="width: 500px;"> <p style="margin: 10px; border: 5px solid blue; padding: 10px; width: 300px; box-sizing: border-box; ">   網上很多設定的方式,目前以二進位的方式來講解(ID CLASS ELEMENT)   網上很多設定的方式,目前以二進位的方式來講解(ID CLASS ELEMENT)   網上很多設定的方式,目前以二進位的方式來講解(ID CLASS ELEMENT) </p></p>

發現內容寬度為:border的寬度+padding的寬度+內容的寬度

4.盒子模型的margin屬性:

如果兩個元素放在一起,對應的margin縱向只取其大的

相關文章

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.