盒模型本质-宽高的底层逻辑

180 阅读2分钟

1 示例代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <title>Examples of margins, padding, and borders</title>
    <style type="text/css">
      ul {
        background: yellow;
        margin: 12px 12px 12px 12px;
        padding: 3px 3px 3px 3px;
        /* No borders set */
      }
      li {
        color: white; /* text color is white */
        background: blue; /* Content, padding will be blue */
        margin: 12px 12px 12px 12px;
        padding: 12px 0px 12px 12px; /* Note 0px padding right */
        list-style: none; /* no glyphs before a list item */
        /* No borders set */
      }
      li.withborder {
        border-style: dashed;
        border-width: medium; /* sets border width on all sides */
        border-color: lime;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>First element of list</li>
      <li class="withborder">
        Second element of list is a bit longer to illustrate wrapping.
      </li>
    </ul>
  </body>
</html>

Note:

• The content widthp. 99 for each LI box is calculated top-down; the containing blockp. 113 for each LI box is established by the UL element.
• The margin box height of each LI box depends on its content heightp. 99, plus top and bottom padding, borders, and margins. Note that vertical margins between the LI boxes collapse.p. 103
• The right padding of the LI boxes has been set to zero width (the 'padding'p. 106 property). The effect is apparent in the second illustration.
• The margins of the LI boxes are transparent — margins are always transparent — so the background color (yellow) of the UL padding and content areas shines through them.
• The second LI element specifies a dashed border (the 'border-style'p. 109 property)
-- copy from CSS 2.1 Specification

杰哥译:

  • 每个li盒子的内容区宽度计算是自顶向下的; 每个li盒子的包含块(containing block)是由ul元素建立的
  • 每个li盒子的margin box高度取决于li元素内容区的高度+上下padding+上下border+上下margin. 注意, 两个li盒子垂直方向的margin合并了
  • li盒子的右padding设置为0, 效果见第二张图
  • li盒子的margin是透明的--margins永远是透明的--因此, ul的填充, 内容区的背景颜色(黄色)穿透了它们(li的margin)
  • 第二个li元素指定了虚线边框

2 重要观点

宽度的计算是自上向下的

高度的计算是自下向上的


重要公式!!!!

包含块的内容区的宽度 = 该元素的margin box的宽度

包含块的内容区的高度 = 所有子元素margin box合并之后的总和

如何理解呢

1) 宽度计算

浏览器先计算html元素的宽度, 再依次计算body> ul > li

首先, 计算html元素的宽度就是浏览器视口(可视窗口)的宽度

然后, 根据公式计算body元素的宽度

body元素的margin box的宽度 = 它的包含块(html元素)的内容区的宽度得到: body的宽度 = 316.8-16 = 300.8依次得到ul的宽度 = 300.8-32-122 = 270.8

再计算第一个li的宽度 = 270.8 -12*2 -12 = 234.8

\

第二个li的宽度 = 270 - 122 - 32 - 12 = 228.8


2) 高度的计算

先计算第一个li的高度

第一个li的margin box的高度 = 12 + 12 + 21.333 + 12 + 12 = 69.333第二个li的高度 = 12 + 3+ 12 + 12 + 3+ 12 + 42.667 = 96.667

ul的内容区的高度 = 96.667+69.333-12 = 154

视频讲解: 盒模型本质-宽高的底层逻辑