Latest web development tutorials

HTML DOM Style margin 屬性

Style 對象參考手冊 Style對象

定義和用法

margin 屬性設置或返回元素的外邊距。

該屬性可使用1 到4 種值:

  • 如果規定一種值,比如:div {margin: 50px} - 所有四個外邊距都是50px。
  • 如果規定兩種值,比如:div {margin: 50px 10px} - 上外邊距和下外邊距是50px,左外邊距和右外邊距是10px。
  • 如果規定三種值,比如:div {margin: 50px 10px 20px}- 上外邊距是50px,左外邊距和右外邊距是10px,下外邊距是20px。
  • 如果規定四種值,比如:div {margin: 50px 10px 20px 30px} - 上外邊距是50px,右外邊距是10px,下外邊距是20px,左外邊距是30px。

語法

設置margin 屬性:

Object.style.margin="%|length|auto|inherit"

返回margin 屬性:

Object.style.margin

描述
% 定义基于父元素宽度的百分比外边距。
length 使用 px、cm 等单位定义外边距的宽度。
auto 浏览器设定的外边距(所有四个外边距是相等的)。
inherit 外边距从父元素继承。


瀏覽器支持

Internet ExplorerFirefoxOperaGoogle ChromeSafari

所有主要瀏覽器都支持margin 屬性。

注意: IE7及更早的版本不支持"inherit"值。IE8 只有規定了!DOCTYPE 才支持"inherit"。 IE9 支持"inherit"。


提示和註釋

margin 屬性和padding 屬性都是在元素周圍插入空間。 然而,不同的是,margin 將圍繞邊框外面插入空間,padding 將在元素邊框內插入空間。


實例

實例

更改div 元素的外邊距:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
<style type="text/css">
div{
    border: 1px solid #FF0000;
}
</style>
<script>
function changeMargin(){
    document.getElementById("ex1").style.margin="100px";
}
function changePadding(){
    document.getElementById("ex2").style.padding="100px";
}
</script>
</head>
<body>

<div id="ex1">这是一些文本。</div>
<br>
<button type="button" onclick="changeMargin()">修改div元素的外边距</button>
<br>
<br>
<div id="ex2">这是一些文本。</div>
<br>
<button type="button" onclick="changePadding()">修改div元素的内边距</button>

</body>
</html>

嘗試一下»


Style 對象參考手冊 Style對象