Latest web development tutorials

HTML DOM Style marginTop 屬性

Style 對象參考手冊 Style對象

定義和用法

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

語法

設置marginTop 屬性:

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

返回marginTop 屬性:

Object.style.marginTop

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


瀏覽器支持

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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

注意: 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.marginTop="100px";
}
function changePadding(){
document.getElementById("ex2").style.paddingTop="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對象