HTML - DOM Style 物件 marginTop 屬性



HTML DOM Style 物件**marginTop**屬性設定或返回元素的頂部邊距。

語法

設定 marginTop 屬性
object.style.marginTop= "percent | length | auto | initial | inherit";
獲取 marginTop 屬性
object.style.marginTop;

屬性值

描述
百分比 它指定父元素寬度的百分比作為頂部邊距。
長度 它指定長度單位作為頂部邊距。
自動 它讓瀏覽器設定頂部邊距值。
初始 它用於將此屬性設定為其預設值。
繼承 它用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示元素的頂部邊距。

HTML DOM Style 物件“marginTop”屬性示例

以下示例設定和獲取 div 元素的頂部邊距。

設定頂部邊距屬性

以下示例使用長度值和百分比設定頂部邊距。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object marginTop Property
    </title>
    <style>
        div {
            border: 2px solid #04af2f;
        }
        #margin {
            border: 1px solid black;
            margin: 15px;
        }
    </style>
</head>
<body>
    <h3>
        Click to set top margin.
    </h3>
    <button onclick="fun()">Set Margin</button>
    <button onclick="funTwo()">
        Set Margin in Percentage
    </button>
    <br>
    <br>
    <div>
        <div id="margin">
            <p>Welcome to Tutorials Point.</p>
        </div>
    </div>
    <script>
        function fun() {
            document.getElementById("margin")
                .style.marginTop = "40px";
        }
        function funTwo() {
            document.getElementById("margin")
                .style.marginTop = "10%";
        }
    </script>
</body>
</html>

獲取頂部邊距屬性

以下示例獲取應用於 div 元素的頂部邊距值。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object marginTop Property
    </title>
    <style>
        div {
            border: 2px solid #04af2f;
        }
        #margin {
            border: 1px solid black;
            margin: 15px;
        }
    </style>
</head>
<body>
    <h3>
        Click to set top margin.
    </h3>
    <button onclick="fun()">Get Margin</button>
    <button onclick="funTwo()">
        Get Margin in Percentage
    </button>
    <br>
    <br>
    <p id="result"></p>
    <br><br>
    <div>
        <div id="margin">
            <p>Welcome to Tutorials Point.</p>
        </div>
    </div>
    <script>
        function fun() {
            let x=document.getElementById("margin")
                .style.marginTop = "40px";
            document.getElementById("result")
                .innerHTML="top Margin: " +x;
        }
        function funTwo() {
            let x =document.getElementById("margin")
                .style.marginTop = "10%";
            document.getElementById("result")
                .innerHTML="top Margin: " +x;
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
marginTop 是 1 是 12 是 1 是 1 是 3.5
html_dom_style_object_reference.htm
廣告