几个概念
line box:包裹 inline box 的一个盒子,一个或多个 line box 堆叠撑起一个 HTML 元素。
inline(-level) box:可以是一个由行内元素包裹的盒子,也可以是一个纯文字的匿名盒子。
content area:对于非替换元素来说,content area 的范围由 font-size 以及字体本身决定;对于替换元素来说,由元素自有宽高决定。
baseline:一个元素基线的位置由该元素内字母 x 底部所在的位置决定,当然字体不同基线所在的位置也就不同。
通过一段代码可以理解一下:
div {
background-color: #ccc;
font-size: 20px;
color: #fff;
}
span {
color: red;
}
<div>文字1<span>文字2</span>文字3</div>
白色的文字就是一个匿名 inline box,红色的文字是一个由
span 包裹的 inline box。这三个 inline box 组成一个 line box,可以理解为灰色的区域,因为在这个例子里就是由一个 line box 撑开了
div。如果有多行的文字,那就有多个 line box。关于 content area,W3C 有一段这样的解释:
CSS 2.1 does not define what the content area of an inline box is (see 10.6.1 above) and thus different UAs may draw the backgrounds and borders in different places.
这篇文章对非替换元素 content area 的定义就是自有宽高加上 margin,padding 以及 border。我认为应该将 content area 理解为 content box。
line box 高度
浏览器会计算 line box 中每一个 inline box 的高度,对于不同的 inline box 计算方式有所不同:
如果是一个替换元素(比如
img,
input),inline-* 元素或者是 flexbox 中的子元素,高度由其 margin box 决定;inline-block 元素:
div {
background-color: #ccc;
color: #fff;
}
span {
display: inline-block;
height: 30px;
margin: 10px;
background: #fff;
color: red;
}
<div>xxx<span>xxx</span>xxx</div>
这里
span inline box 的高度就是 height + margin 2。如果 height 的值是 auto,高度就是等于 line-height + margin 2。如果是一个非替换元素,高度由它的 line-height 决定,而不是 content area,虽然有时候看起来像 content area 撑开了 line box 的高度。










