4 回答
解释:
这里发生了一些事情。
在您的示例中,该small
元素是一个内联级元素,这意味着它的垂直对齐方式由该vertical-align
属性确定。
默认vertical-align
值为baseline
,表示small
元素的基线将与父框的基线对齐:
将框的基线与父框的基线对齐。如果框没有基线,则将底部边距边缘与父项的基线对齐。
接下来,您需要考虑line-height
属性及其计算方式。您还需要考虑领先和半领先。在 CSS 中,半前导是通过找出元素的line-height
和之间的差异font-size
,将其分成两半,然后将计算出的空间量放置在文本上方和下方来确定的。
为了说明,这里有一个示例图像展示了这一点(取自 W3.org):
由于line-height
is 20px
,并且small
元素具有font-size
of 13px
,那么我们可以确定在元素文本的3.5px
上方和下方添加了空格:small
(20px - 13px) / 2 = 3.5px
font-size
同样,如果我们计算具有 a of的周围文本节点的半前导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
单位。
由于 thefont-size
是16px
和所需的line-height
值是20px
,您将除以line-height
thefont-size
并得到1.25
:
p { line-height: 1.25; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
如果您不想使用 relative 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>
Josh Crozier 发布的答案的替代方法是一起重置小行高:
p { line-height: 20px }
small {line-height: initial;}
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
您可以使用相对值line-height
。在您的情况下,基本字体大小为 16px,因此相对单位为 20px 的行高为1.25
p { line-height: 1.25; }
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>
发生这种情况是因为 small 标签的 font-size:smaller 和 p 标签的尺寸比 small 标签大,所以 small 标签和 p 标签的差异造成了这个问题。当您将小标签放入 p 标签时,请增加高度,因为小标签占用空间小,然后是 p 标签。
解决这个问题,你必须给小标签 19px 的行高,像这样:
p { line-height: 20px }
small{line-height: 19px}
<p>some normal-sized text</p>
<p>some <small>small</small>-sized text</p>