css盒子模型

67 阅读1分钟

什么是盒模型:

html每一个元素,每个容器都被认为一个盒子模型。每一个盒子模型都包含,content,padding,border,margin 这四部分。 目前盒子模型有两种类型:1、标准盒子模型 box-sizing:content-box 2、IE盒子模型 box-sizing:border-box。默认是标准盒子模型。可以通过 box-sizing属性自定义使用哪种盒子模型。

标准盒模型与IE盒模型的区别:

标准盒模型

使用标准盒模型时,给html元素设置的width值 = content的宽度,给html元素设置的height = content的高度。html元素width值不受影响, width: 100px;为html元素的宽度。实际宽高 由 width content,padding,border这四部分决定。

  <style>
        div{
            width: 100px;
            height: 100px;
        }
        .a {background-color: red;}
        .b { background-color: yellow;}
    </style>

<body>
    <div class="a"'>我是盒子模型</div>
    <div class="b">我是盒子模型</div>
    <script>
        document.querySelector(".a").addEventListener("click", displayDate);
        function displayDate(){
            var h = document.querySelector(".a").offsetHeight;  //高度
            var w = document.querySelector(".a").offsetWidth;  //宽度
            console.log('实际宽度',h)
            console.log('实际高度',w)
     }
    </script>
</body>

1642153965(1).png

添加padding margin border 时,实际宽高:

   <style>
        div{
            width: 100px;
            height: 100px;
        }
        .a {
            background-color: red;
            padding:2px;
            margin:3px;
            border:5px solid yellow
        }
        .b { background-color: yellow;}
    </style>

<body>
    <div class="a"'>我是盒子模型</div>
    <div class="b">我是盒子模型</div>
    <script>
        document.querySelector(".a").addEventListener("click", displayDate);
        function displayDate(){
            var h = document.querySelector(".a").offsetHeight;  //高度
            var w = document.querySelector(".a").offsetWidth;  //宽度
            console.log('实际宽度',h)
            console.log('实际高度',w)
     }
    </script>
</body>

1642154200(1).png

IE盒模型

使用IE盒模型时,给html元素的 width值 受padding,border,margin影响。width: 100px;是盒模型在页面上占据的宽度大小;即实际宽高 = 设置的width值。

    <style>
        div{
            width: 100px;
            height: 100px;
        }
        .a {
            background-color: red;
            padding:2px;
            margin:3px;
            border:5px solid yellow;
            box-sizing:border-box;
        }
        .b { background-color: yellow;}
    </style>

<body>
    <div class="a"'>我是盒子模型</div>
    <div class="b">我是盒子模型</div>
    <script>
        document.querySelector(".a").addEventListener("click", displayDate);
        function displayDate(){
            var h = document.querySelector(".a").offsetHeight;  //高度
            var w = document.querySelector(".a").offsetWidth;  //宽度
            console.log('实际宽度',h)
            console.log('实际高度',w)
     }
    </script>
</body>

1642154335(1).png