一、计算div盒模型宽高
div盒模型宽度 = width + 左右padding + 左右border(不包含左右margin)
div盒模型高度 = height + 上下padding + 上下border(不包含上下margin)
<!DOCTYPE html>
<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>
<style>
.box{
width: 100px;
height: 100px;
margin: 20px;
padding: 20px;
background-color: #ccc;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script>
var box=document.getElementById('box');
console.log('box的宽度为:' + box.offsetWidth + 'px');
console.log('box的高度为:' + box.offsetHeight + 'px');
</script>
</body>
</html>
二、固定div盒模型宽高
设置box-sizing: border-box;使div盒模型宽度 = width ,div盒模型高度 = height 。
<!DOCTYPE html>
<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>
<style>
.box{
width: 100px;
height: 100px;
margin: 20px;
padding: 20px;
background-color: #ccc;
border: 1px solid #000;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script>
var box=document.getElementById('box');
console.log('box的宽度为:' + box.offsetWidth + 'px');
console.log('box的高度为:' + box.offsetHeight + 'px');
</script>
</body>
</html>