HTML - DOM樣式物件marginRight屬性



HTML DOM 樣式物件**marginRight**屬性設定或返回元素的右邊距。

語法

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

屬性值

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

返回值

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

HTML DOM 樣式物件“marginRight”屬性示例

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

設定右邊距屬性

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

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object marginRight Property
    </title>
    <style>
        div {
            border: 2px solid #04af2f;
        }
        #margin {
            border: 1px solid black;
            margin: 15px;
        }
    </style>
</head>
<body>
    <h3>
        Click to set right 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.marginRight = "40px";
        }
        function funTwo() {
            document.getElementById("margin")
                .style.marginRight = "10%";
        }
    </script>
</body>
</html>

獲取右邊距屬性

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

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        div {
            border: 2px solid #04af2f;
        }
        #margin {
            border: 1px solid black;
            margin: 15px;
        }
    </style>
    <title>
        HTML DOM Style Object marginRight Property
    </title>
</head>
<body>
    <h3>
        Click to set right 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.marginRight = "40px";
            document.getElementById("result")
                .innerHTML="right Margin: " +x;
        }
        function funTwo() {
            let x =document.getElementById("margin")
                .style.marginRight = "10%";
            document.getElementById("result")
                .innerHTML="right Margin: " +x;
        }
    </script>
</body>
</html>

支援的瀏覽器

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