HTML - DOM Style 物件 margin 屬性



HTML DOM Style 物件的 **margin** 屬性設定或返回元素的邊距。我們可以為各個邊設定邊距。

它最多接受四個值

  • **一個值:**對於一個值,所有四個邊距都將相同。例如:div {margin: 20px}。
  • **兩個值:**對於兩個值,頂部和底部邊距將相同,左側和右側邊距將相同。例如:div {margin: 20px 40px}。
  • **三個值:**對於三個值,頂部和底部邊距將具有不同的尺寸,而左側和右側邊距將具有相同的尺寸。例如:div {margin: 20px 40px 60px}。
  • **四個值:**對於四個值,所有邊距都將具有不同的尺寸。例如:div {margin: 20px 40px 60px 10%}。

語法

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

屬性值

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

返回值

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

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

以下示例為 div 元素設定邊距。

為 div 元素設定邊距

此示例為 div 元素的所有邊設定相同的邊距。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object margin Property
    </title>
</head>
<body>
    <style>
        div {
            border: 2px solid #04af2f;
        }
    </style>
    <h3>
        Click to set line height.
    </h3>
    <button onclick="fun()">Set Margin</button>
    <br>
    <br>
    <div id="margin">
        <p>Welcome to Tutorials Point.</p>
    </div>
    <script>
        function fun() {
            document.getElementById("margin")
                .style.margin = "20px";
        }
    </script>
</body>
</html>

為 div 元素設定不同的邊距

此示例為 div 元素的不同邊設定不同的邊距。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object margin Property
    </title>
</head>
<body>
    <style>
        div {
            border: 2px solid #04af2f;
        }
        #margin {
            border: 1px solid black;
        }
    </style>
    <h3>
        Click to set line height.
    </h3>
    <button onclick="fun()">Set Margin</button>
    <button onclick="funTwo()">Two Values</button>
    <button onclick="funThree()">Three Values</button>
    <button onclick="funFour()">Four values</button>
    <br>
    <br>
    <div>
    <div id="margin">
        <p>Welcome to Tutorials Point.</p>
    </div>
    </div>
    <script>
        function fun() {
            document.getElementById("margin")
                .style.margin = "20px";
        }
        function funTwo() {
            document.getElementById("margin")
                .style.margin = "20px 40px";
        }
        function funThree() {
            document.getElementById("margin")
                .style.margin = "20px 40px 60px";
        }
        function funFour() {
            document.getElementById("margin")
                .style.margin = "20px 40px 30px 20%";
        }
    </script>
</body>
</html>

支援的瀏覽器

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