Skip to content

盒模型宽度计算

盒模型宽度计算

  • offsetWidth =(内容宽度+内边距+边距),无外边距
  • box-sizing:border-box; 可以改变盒模型宽度

box-sizing: content-box 是 W3C 标准盒子模型

box-sizing: border-box 是 IE 怪异盒子模型

html
<!-- item 的 offsetWidth 是多大? -->
<style>
  #item {
    width: 100px;
    padding: 10px;
    border: 1px solid #ccc;
    margin: 10px;
  }
</style>
<div id="item"></div>
<script>
  let itemOffSetWidth = document.getElementById('item').offsetWidth;
  console.log('itemOffSetWidth', itemOffSetWidth);
</script>

offsetWidth = 122px;

如果让 offsetWidth 等于100px,不修改width、padding 、border等,应该怎么做?

使用box-sizing: border-box;

css
<style>
#item {
    width: 100px;
    padding: 10px;
    border: 1px solid #ccc;
    margin: 10px;
    box-sizing: border-box;
}
</style>

基于 MIT 许可发布