margin 是 margin-top、margin-right、margin-bottom、margin-left 的縮寫,用來表明外邊距的大小。它的值可以是寬度值、百分比或 auto,其中寬度值必須帶單位。
1. 依上、右、下、左順序賦四個值:
- margin: 1px 2px 3px 4px;
等同於 top 為 1px、right 為 2px、bottom 為 3px、left 為 4px。記住從上方開始順時針旋轉一圈。
2. 依上下、左右順序賦兩個值:
- margin: 1px 2px;
等同於 top 與 bottom 為 1px、right 與 left 為 2px。這種寫法同樣適用於 padding、border-width、border-color 等。
非 table 類型的元素,以及 table 類型中的 table-caption、table 與 inline-table 三類。例如 TD、TR、TH 等,margin 並不適用。
對於行內非替換元素(如 SPAN),垂直方向的 margin 不起作用:
- <div style="border:1px solid red;">
- <span style="margin:100px; background:gray;">ddd</span>
- </div>
可以看到 DIV 的上下 border 緊貼著灰色的 SPAN 元素。
垂直方向上不同元素相鄰的 margin 在某些情況下會發生折疊。例如兩個上下相鄰的 div,上面的 margin-bottom 會與下面的 margin-top 合併,取較大者:
- <div style="background-color:green; width:100px; height:100px;margin-bottom:100px;"></div>
- <div style="background-color:red; width:100px; height:100px; margin-top:50px;"></div>
上下兩個 DIV 最終相距 100px,而不是 150px。