CSS box width = margin-left + border-left + padding-left + width(content width) + padding-right + border-right + margin-right;
CSS box height = margin-top + border-top + padding-top + width(content width) + padding-bottom + border-bottom + margin-bottom;
<style>
.box {
margin: 10px 20px 30px 40px;
padding: 10px 20px 30px 40px;
width: 200px;
height: 300px;
border: 8px solid #000;
background: green;
}
</style>
<div class="box" id="box">box</div>
<script>
const $box = document.querySelector("#box");
const $boxRect = $box.getBoundingClientRect();
console.log($boxRect.width === 200 + 20 + 40 + 8 * 2); // true
console.log($boxRect.height === 300 + 10 + 30 + 8 * 2); // true
</script>
$Element.getBoundingClientRect()
API 可以获得 CSS 盒模型的在页面上的具体信息。
实际内容宽度 = width
- border-width
- padding
;
<style>
.box {
margin: 10px 20px 30px 40px;
padding: 10px 20px 30px 40px;
width: 200px;
height: 300px;
border: 8px solid rgba(0, 0, 0, 0.3);
background: green;
}
</style>
<div class="box" id="box">box</div>
<script>
const $box = document.querySelector("#box");
const $boxRect = $box.getBoundingClientRect();
console.log($boxRect.width === 200); // true
console.log($boxRect.height === 300); // true
</script>