外邊距 margin 指的是邊框到父元素或同級元素之間的那段距離。它決定的是「盒子與外界」的間隔。
從 CSS 盒子模型來看,外邊距同樣分為四個方向:margin-top、margin-right、margin-bottom、margin-left。這點和內邊距 padding 完全一致。
語法:
margin-top:像素值; margin-right:像素值; margin-bottom:像素值; margin-left:像素值;
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS外邊距margin屬性</title>
<style type="text/css">
#main { display:inline-block;/*將塊元素轉換為inline-block元素*/ border:1px solid #CCCCCC; }
.lvye { display:inline-block; /*將塊元素轉換為inline-block元素*/ padding:20px; margin-top:20px; margin-right:40px; margin-bottom:60px; margin-left:80px; border:1px solid red; background-color:#FCE9B8; }
span{border:1px solid blue;background-color:#C5FCDF;}
</style>
</head>
<body>
<div id="main">
<div class="lvye"><span> 學習網</span></div>
</div>
</body>
</html>
在瀏覽器中預覽,效果如下:
四個方向各自獨立設定,缺點是代碼冗長。實務上我們幾乎只用下面的簡潔寫法。
margin 有三種簡潔寫法:
語法:
margin:像素值; margin:像素值1 像素值2; margin:像素值1 像素值2 像素值3 像素值4;
例如:
「margin:20px;」表示四個方向的外邊距都是 20px;
「margin:20px 40px;」表示 margin-top 與 margin-bottom 為 20px,margin-right 與 margin-left 為 40px;
「margin:20px 40px 60px 80px;」表示上 20px、右 40px、下 60px、左 80px。依照順時針方向記憶即可。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS外邊距margin屬性</title>
<style type="text/css">
#main { display:inline-block;/*將塊元素轉換為inline-block元素*/ border:1px solid #CCCCCC; }
.lvye { display:inline-block; /*將塊元素轉換為inline-block元素*/ padding:20px; margin:40px 80px; border:1px solid red; background-color:#FCE9B8; }
span{border:1px solid blue;background-color:#C5FCDF;}
</style>
</head>
<body>
<div id="main">
<div class="lvye"><span> 學習網</span></div>
</div>
</body>
</html>
在瀏覽器中預覽,效果如下:
這裡用「margin:40px 80px;」一行,就等價於前面四行的分方向寫法,代碼量立刻減半。養成用簡潔寫法的習慣,你的樣式表會乾淨很多。