css面试题

57 阅读1分钟

你对盒子模型理解多少?

盒子模型是指元素在网页中实际占据的大小

盒子模型的计算方式

盒子模型 = width/height+padding+border 注意:没有margin

使用js获取盒子模型大小(offsetWidth)

JavaScript中获取盒子模型的方式是 obj.offsetWidth / offsetHeight

代码

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>盒子模型</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
     /* 盒子模型=width+padding*2+border*2 */
    div{
        width: 200px;
        height: 200px;
        padding: 10px;
        border: 5px solid red;
        background-color: #ccc;
        box-sizing: border-box ;
    }
</style>
<body>
    <div id="box">盒子模型</div>
    <script>
        let w = document.getElementById("box").offsetWidth
        console.log(w);
    </script>
</body>
</html>