寫 CSS 排版,最常打交道的就是尺寸與間距這幾個屬性。以下從最基礎的開始整理。
<div style="width: 200px; height: 200px; background-color: black;"></div>
這兩個屬性設定 DIV 的寬與高。要注意的是,在標準盒模型下它們指的是內容區的尺寸,padding 與 border 會另外加上去。若希望 width 代表元素實際佔據的總寬度,在全域樣式中加上:
* { box-sizing: border-box; }
<div style="background-color: black; width: 500px; height: 500px;">
<div style="margin: 5px 10px 20px 30px; width: 200px;
height: 200px; background-color: white;"></div>
</div>
margin 決定元素到父容器(或相鄰元素)的距離,這個區域是透明的,不會被填色。簡寫的四個值依序為上、右、下、左。觀察範例中白色 DIV 距黑色 DIV 四邊的距離,就能對應到這四個數字。
margin-left: 50px; /* 到父容器左邊框的距離 */
margin-right: 10px; /* 到父容器右邊框的距離 */
margin-top: 50px; /* 到父容器上邊框的距離 */
margin-bottom: 10px; /* 到父容器下邊框的距離 */
<div style="width: 500px; height: 500px; background-color: black;">
<div style="margin-left: 50px; margin-top: 50px;
width: 200px; height: 200px; background-color: white;"></div>
</div>
第一,margin 可以為負值,padding 不行。負 margin 是許多進階技巧的基礎,例如把元素往外拉、讓相鄰元素重疊,前面介紹過的等高方案就用到了這個特性。
第二,垂直方向的 margin 會發生折疊(collapsing)。兩個上下相鄰的塊級元素,它們之間的 margin-bottom 與 margin-top 不會相加,而是取較大值。這解釋了「為什麼我設了 20px 卻只空出 20px 而不是 40px」這個經典困惑。若不想受折疊影響,改用 padding,或讓父元素建立 BFC(例如設 overflow: hidden 或 display: flow-root)。