解释:
这里发生了一些事情。
在你的例子中,small
元素是一个行内元素 https://www.w3.org/TR/CSS2/visuren.html#inline-level,这意味着它的垂直对齐方式由vertical-align财产 https://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align.
默认vertical-align
值为baseline
,这意味着基线small
元素将与父框的基线对齐:
将框的基线与父框的基线对齐。如果该框没有基线,请将下边距边缘与父级的基线对齐。
接下来,您需要考虑line-height财产 https://www.w3.org/TR/CSS2/visudet.html#propdef-line-height以及它是怎样的计算出的 https://www.w3.org/TR/CSS2/visudet.html#line-height。您还需要采取领先和半领先 https://www.w3.org/TR/CSS2/visudet.html#leading考虑到。在 CSS 中,半前导是通过查找元素之间的差异来确定的line-height
and font-size
,将其分成两半,然后将计算出的空间量放置在文本上方和下方。
为了便于说明,这里有一个示例图像演示了这一点(取自 W3.org https://www.w3.org/Talks/2008/0911-CSS-Amsterdam/line-height.png):
自从line-height
is 20px
,以及small
元素有一个font-size
of 13px
,那么我们可以确定3.5px
的上方和下方添加了空间small
元素的文本:
(20px - 13px) / 2 = 3.5px
同样,如果我们计算周围文本节点的半前导,其具有font-size
of 16px
,那么我们可以确定2px
在周围文本的上方和下方添加了一定的空间。
(20px - 16px) / 2 = 2px
现在,如果我们将这些半领先空间计算与vertical-align
属性,您会注意到实际上在基线下方添加了更多空间small
元素。这解释了为什么计算出的高度p
元素包含small
元素大于另一个元素的计算高度p
元素。
话虽这么说,您会期望计算出的高度p
元素继续增加font-size
of the small
元素减少。为了进一步说明这一点,您会注意到计算出的高度p
元素是23px
当。。。的时候font-size
of the 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
元素aline-height
of 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
units.
自从font-size
is 16px
和想要的line-height
值为20px
,你会划分line-height
by the 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>