margin(外距)是 CSS 中用來控制元素之間距離的屬性,它能在一個宣告中設定所有外距,而這些間距本身是透明不可見的。
margin 同樣拆成四個方向:margin-left(距左元素塊的距離)、margin-top(距頂部元素塊的距離)、margin-right(距右元素塊的距離)、margin-bottom(距底部元素塊的距離)。
margin-left: margin-left:10px; 表示距左側元素塊 10 像素,也可寫成 margin-left:10%; 代表左側 10%。
margin-right: margin-right:10px; 表示距右側元素塊 10 像素,可用 margin-right:10%; 表示右側 10%。
margin-top: margin-top:10px; 表示距頂部元素塊 10 像素,可用 margin-top:10%; 表示頂部 10%。
margin-bottom: margin-bottom:10px; 表示距底部元素塊 10 像素,可用 margin-bottom:10%; 表示底部 10%。
注意:屬性名稱中間用「-」連接,設定值時用「:」,並以「;」結尾,全部使用小寫半角字母。
當上下左右都要設定 margin 時,可用簡寫精簡程式碼:
margin:10px; 代表上下左右元素塊距離皆為 10px。
margin:5px 10px; 代表上下元素塊距離 5px、左右距離 10px。
margin:5px 6px 7px; 代表上 5px、左右 6px、下 7px。
margin:5px 6px 7px 8px; 代表上 5px、右 6px、下 7px、左 8px。
其中四值寫法依「順時針」順序排列:上、右、下、左。
以上就是 margin 的屬性與用法總結,其運用邏輯與 padding 一致。