HTML - DOM Style 物件 boxSizing 屬性



HTML DOM Style 物件 **boxSizing** 屬性指定元素的總寬度和高度的計算方式。

語法

設定 boxSizing 屬性
object.style.boxSizing= "border-box | content-box | initial | inherit";
獲取 boxSizing 屬性
object.style.boxSizing;

屬性值

描述
border-box 在 border-box 中,指定的寬度保持不變,元素上指定的任何填充或邊框都包含在內並在指定的寬度和高度內繪製。內容的高度和寬度透過從指定的“width”和“height”屬性中減去相應側面的邊框和填充寬度來計算。
content-box 這是預設值,指定的寬度和高度分別應用於元素的內容框的寬度和高度。任何填充或邊框寬度都將新增到內容框的最終寬度。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示元素的 boxSizing 屬性。

HTML DOM Style 物件“boxSizing”屬性的示例

以下示例說明了在 div 元素上實現 boxSizing 屬性。

向元素新增“border-box”屬性

此示例說明了 border-box 屬性的使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .parent {
            width: 400px;
            border: 2px solid;
        }
        .child {
            width: 200px;
            border: 4px solid #04af2f;
            float: left;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child" id="child1">BOX 1.</div>
        <div class="child" id="child2">Box 2.</div>
        <div class="child" id="child3">Box 3.</div>
        <div style="clear:both;"></div>
    </div>
    <button onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {
            document.getElementById("child1")
                .style.boxSizing = "border-box";
            document.getElementById("child2")
                .style.boxSizing = "border-box";
            document.getElementById("child3")
                .style.boxSizing = "border-box";                
        }
    </script>
</body>
</html>

向元素新增“content-box”屬性

此示例說明了 content-box 屬性的使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .parent {
            width: 400px;
            height: 450px;
            border: 2px solid;
        }
        .child {
            width: 200px;
            height: 100px;
            border: 4px solid #04af2f;
            float: left;
            padding: 10px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child" id="child1">BOX 1.</div>
        <div class="child" id="child2">Box 2.</div>
        <div class="child" id="child3">Box 3.</div>
        <div style="clear:both;"></div>
    </div>
    <button onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {
            document.getElementById("child1")
                .style.boxSizing = "content-box";
            document.getElementById("child2")
                .style.boxSizing = "content-box";
            document.getElementById("child3")
                .style.boxSizing = "content-box";                
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
boxSizing 是 10 是 12 是 29 是 5.1 是 7
html_dom_style_object_reference.htm
廣告