Nemo
Nemo
Published on 2025-02-11 / 6 Visits
0
0

CSS之box-sizing

/*
 *  box-sizing 属性定义了如何计算一个元素的总宽度和总高度。
 *  它主要影响元素尺寸的计算方式,特别是当元素设置了 padding 和 border 时。
 *
 *  有三个可能的值:
 *
 *  1. content-box (默认值)
 *     - 元素的 width 和 height 属性仅包含内容区域的宽度和高度。
 *     - padding 和 border 会增加元素的总尺寸。
 *     - 总宽度 = width + padding-left + padding-right + border-left + border-right
 *     - 总高度 = height + padding-top + padding-bottom + border-top + border-bottom
 *
 *  2. border-box
 *     - 元素的 width 和 height 属性包含内容区域、padding 和 border。
 *     - 元素的总尺寸由 width 和 height 直接决定,padding 和 border 会“挤压”内容区域。
 *     - 内容区域的尺寸会随着 padding 和 border 的增加而减小。
 *     - 总宽度 = width
 *     - 总高度 = height
 *
 *  3. inherit
 *     - 从父元素继承 box-sizing 属性的值。
 */

/* 示例:使用 content-box (默认) */
.content-box-example {
  width: 200px;
  height: 100px;
  padding: 20px;
  border: 10px solid black;
  box-sizing: content-box; /* 显式设置,虽然默认就是 content-box */
  /*
   *  总宽度 = 200px + 20px + 20px + 10px + 10px = 260px
   *  总高度 = 100px + 20px + 20px + 10px + 10px = 160px
   */
}

/* 示例:使用 border-box */
.border-box-example {
  width: 200px;
  height: 100px;
  padding: 20px;
  border: 10px solid black;
  box-sizing: border-box;
  /*
   *  总宽度 = 200px
   *  总高度 = 100px
   *  内容区域的宽度 = 200px - 20px - 20px - 10px - 10px = 140px
   *  内容区域的高度 = 100px - 20px - 20px - 10px - 10px = 40px
   */
}

/* 示例:使用 inherit */
.parent {
  box-sizing: border-box;
}

.child {
  width: 100px;
  height: 50px;
  padding: 10px;
  border: 5px solid red;
  box-sizing: inherit; /* 继承父元素的 border-box */
  /*
   *  由于继承了 border-box,总宽度 = 100px,总高度 = 50px
   */
}

/*
 *  建议:通常使用以下方式来重置所有元素的 box-sizing 为 border-box,
 *  这使得页面布局更容易控制和预测。
 */
html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

总结:

  • content-box: 默认值,width/height 只包含内容区域。

  • border-box: width/height 包含内容、padding 和 border。 推荐使用,更容易控制元素的总尺寸。

  • inherit: 从父元素继承。

通常建议全局设置 box-sizing: border-box,可以避免在计算元素大小时出现混淆。


Comment