04 盒模型宽度计算
html
<!-- 如下代码,请问 div1 的 offsetWidth 是多大? -->
<style type="text/css">
#div1 {
width: 100px;
padding: 10px;
border: 1px solid #ccc;
margin: 10px;
/* box-sizing: border-box; */
}
</style>
<div id="div1">this is div1</div>
<script>
// document.getElementById('div1').offsetWidth
</script>offsetWidth 是元素在页面上占据的总宽度,包括内容宽度、内边距(padding)、边框(border)和垂直滚动条(如果有)。
width: 100px是内容宽度。padding: 10px是内边距,左右各 10px。border: 1px solid #ccc是边框,左右各 1px。
计算 offsetWidth 时需要把这些值加起来:内容宽度 + 左右内边距 + 左右边框宽度。也就是:100px(内容宽度) + 10px(左内边距) + 10px(右内边距) + 1px(左边框) + 1px(右边框) = 122px。
所以,div1 的 offsetWidth 是 122px。
- 如果没设置
box-sizing: border-box;属性,浏览器使用的是默认的内容盒模型(content-box),那么offsetWidth = width + padding * 2 + border * 2(没有外边距margin)。答案是 122px。 - 如果设置了
box-sizing: border-box;属性,那么offsetWidth = width。答案是 100px。