margin 家族包含 margin-top、margin-right、margin-bottom、margin-left 與 margin 本身。要分別定義網頁的上下左右邊距,主要有兩種寫法。
四邊各給不同值時,順序固定是「上、右、下、左」,即順時針方向:
margin: top-value right-value bottom-value left-value;
或者拆成四條獨立宣告:
margin-top: value; margin-right: value; margin-bottom: value; margin-left: value;
當四邊數值一致時,只寫一個值即可:
margin: value;
例如 margin: 10px 20px 20px 40px; 表示上、右、下、左邊距分別為 10、20、20、40。
也可以寫成:
margin-top: 10px; margin-right: 20px; margin-bottom: 20px; margin-left: 40px;
兩者效果完全相同,可依可讀性需求挑選。
以下是我們經常使用的 div + CSS 版型結構,讓頁首與導航列之間保留 5px 間距:
<style type="text/css">
<!--
#header {
height: 120px;
width: 960px;
background-image: url(headPic.gif);
background-repeat: no-repeat;
margin: 0 0 5px 0;
}
-->
</style>
<div id="header"></div><!-- 網站的頭部 -->
<div id="nav"></div><!-- 網站的導航 -->
<div id="content"></div><!-- 網站內容 -->
<div id="footer"></div><!-- 網站底部 -->
這裡的 margin: 0 0 5px 0 只替下邊留出間距,其餘三邊歸零,避免瀏覽器預設樣式帶來的意外空白。