我有以下 fiddle :
http://jsfiddle.net/tompazourek/sn5jp/
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
p { line-height: 20px }
当我在 Chrome 中检查页面时,我发现第一段的计算高度是 20px,但第二段的计算高度是 21px。
为什么是
<small>
标签导致这些问题? 我该如何解决这个问题? 每次出现
<small>
段落中的文字搞乱了我的baseline grid .编辑:后来我还发现了一篇与这个话题相关的有趣文章:Deep dive CSS: font metrics, line-height and vertical-align .
最佳答案
解释:
这里发生了一些事情。
在您的示例中, small
元素是 inline-level element ,这意味着它的垂直对齐方式由 vertical-align
property 决定.
默认vertical-align
值为 baseline
,这意味着 small
的基线元素将与父框的基线对齐:
Align the baseline of the box with the baseline of the parent box. If the box does not have a baseline, align the bottom margin edge with the parent's baseline.
接下来,您需要考虑
line-height
property以及它是如何calculated .您还需要带leading and half-leading考虑到。在 CSS 中,半前导是通过查找元素的 line-height
之间的差异来确定的。和 font-size
,将其一分为二,然后将计算出的空间量放在文本上方和下方。为了便于说明,这里有一个示例图像( taken from W3.org ):
自
line-height
是 20px
,以及 small
元素有一个 font-size
的 13px
,那么我们可以确定 3.5px
在 small
的上方和下方添加了空间元素的文本:(20px - 13px) / 2 = 3.5px
同样,如果我们计算周围文本节点的半前导,其具有
font-size
的 16px
,那么我们可以确定 2px
在周围文本的上方和下方添加空格。(20px - 16px) / 2 = 2px
现在,如果我们将这些半领先的空间计算与
vertical-align
联系起来。属性,您会注意到实际上在 small
的基线下方添加了更多空间。元素。这解释了为什么 p
的计算高度包含 small
的元素元素大于另一个 p
的计算高度元素。话虽如此,您会期望
p
的计算高度元素继续增加为font-size
的small
元素减少。为了进一步说明这一点,您会注意到 p
的计算高度元素是 23px
当font-size
的small
元素设置为 6px
.p { line-height: 20px; }
small { font-size: 6px; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
潜在的解决方法:
因为我们知道高度差是由添加到
baseline
的额外空间引起的。 ,我们可以更改 vertical-align
small
的值元素到 top
:p { line-height: 20px; }
small { vertical-align: top; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
或者,您可以提供
small
元素 a line-height
的 17px
,这将导致 2px
在元素上方和下方添加的空间(与我们上面计算的为周围文本添加的空间相同)。// Surrounding text that is 16px:
(20px - 16px) / 2 = 2px
// Small element text that is 13px:
(17px - 13px) / 2 = 2px
p { line-height: 20px; }
small { line-height: 17px; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
但是,您真的不想计算其中的任何内容并对其进行硬编码,这意味着您应该只使用相对
line-height
并省略 px
单位。自
font-size
是 16px
和所需的 line-height
值为 20px
,您将分割 line-height
由 font-size
并获得 1.25
:p { line-height: 1.25; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
如果您不想使用亲戚
line-height: 1.25
,并且您想继续使用 line-height: 20px
,那么你当然可以重置 small
元素的 line-height
值回到初始值,即normal
.p { line-height: 20px; }
small { line-height: normal; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
关于html - <small> 标签使段落高度变大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23461423/