每個HTML元素都可以看作裝了東西的盒子
盒子具有寬度(width)和高度(height)
盒子里面的內容到盒子的邊框之間的距離即填充(margin)
盒子本身有邊框(border)
而盒子邊框外和其他盒子之間,還有邊界(margin)
內容填充屬性(padding)
Padding-top
上填充
Padding-bottom
下填充
Padding-left
左填充
Padding-right
右填充
Demo1:
代碼:
<div class="oDiv1">
padding
</div>
.oDiv1{width: 200px;height: 200px;background: red;}
設置padding后的
Demo2:
代碼:
.oDiv1{width: 100px;height: 100px;background: red;padding: 100px 0 0 100px;}
Demo3:
代碼:
<div class="oDiv1">
<div class="oDiv2">
padding
</div>
</div>
.oDiv1{width: 200px;height: 200px;background: red;}
.oDiv2{width: 100px;height: 100px;background: yellow;}
Demo4:
代碼:
.oDiv1{width: 200px;height: 200px;background: red;padding: 100px 0 0 100px;}
.oDiv2{width: 100px;height: 100px;background: yellow;}
Demo5:
代碼:
.oDiv1{width: 200px;height: 200px;background: red;}
.oDiv2{width: 100px;height: 100px;background: yellow;padding: 50px 0 0 50px;}
注:由以上的例子可以看出padding的作用域是,如果對於某一個盒子設置了padding屬性,它會把這個盒子撐大,如果想把這個盒子變成原來的大小,只有把盒子原來設置的寬高減去padding的對應值就行,還有一個需要注意的問題是,對於一個盒子,如果它的外部還有一個盒子,並且這兩個盒子都設置了寬高,如果此時我們對內部的盒子設置padding,這是,padding影響的只是內部的盒子,對外部的盒子沒有影響。
外邊距屬性(margin):
margin-top
上填充
margin-bottom
下填充
Margin-left
左填充
Margin-right
右填充
Demo1:
代碼:
<div class="oDiv1"></div>
<div class="oDiv2"></div>
.oDiv1{width: 100px; height: 100px;background: red;}
.oDiv2{width: 100px; height: 100px; background: yellow;}
Demo2:
代碼:
.oDiv1{width: 100px; height: 100px;background: red;}
.oDiv2{width: 100px; height: 100px; background: yellow;margin-top: 50px;}
Demo3:
代碼:
<div class="oDiv1">
<div class="oDiv2">
</div>
</div>
.oDiv1{width: 200px; height: 200px;background: red;}
.oDiv2{width: 100px; height: 100px; background: yellow;}
Demo4:
代碼:
.oDiv1{width: 200px; height: 200px;background: red;}
.oDiv2{width: 100px; height: 100px; background: yellow;margin-left: 50px;}
注:從以上例子可以看出,對於一個盒子設置了margin后,對於這個這個盒子,看似沒有影響,只是增加了這個盒子的外邊距,沒有影響盒子的寬高,其實,這個盒子的寬高也變大了,因為我們只是以盒子的背景顏色來判斷盒子的大小,其實,盒子的背景顏色只是由內容,內邊距,和邊框組成的區域,而外邊距的顏色默認為透明的。我們平時設置盒子的寬高,只是這個盒子所包裹的內容區域的寬高,其實盒子的真實大小是由盒子的內外邊距,盒子的內容寬高(也就是我們最初設置盒子的寬高)和邊框的綜合。我們一旦對於這個盒子設置了寬高后,盒子的內容寬高不會改變,但盒子的真實寬高卻會發生改變的。
用Margin還是用Padding
何時應當使用margin:需要在border外側添加空白時。空白處不需要背景(色)時。上下相連的兩個盒子之間的空白,需要相互抵消時。如15px + 20px的margin,將得到20px的空白。
何時應當時用padding:需要在border內測添加空白時。空白處需要背景(色)時。上下相連的兩個盒子之間的空白,希望等於兩者之和時。如15px + 20px的padding,將得到35px的空白。
個人認為:margin是用來隔開元素與元素的間距;padding是用來隔開元素與內容的間隔。margin用於布局分開元素使元素與元素互不相干;padding用於元素與內容之間的間隔,讓內容(文字)與(包裹)元素之間有一段“呼吸距離”。