13
4

4 回答 4

13

解释:

这里发生了一些事情。

在您的示例中,该small元素是一个内联级元素,这意味着它的垂直对齐方式由该vertical-align属性确定。

默认vertical-align值为baseline,表示small元素的基线将与父框的基线对齐:

将框的基线与父框的基线对齐。如果框没有基线,则将底部边距边缘与父项的基线对齐。

接下来,您需要考虑line-height属性及其计算方式。您还需要考虑领先和半领先。在 CSS 中,半前导是通过找出元素的line-height和之间的差异font-size,将其分成两半,然后将计算出的空间量放置在文本上方和下方来确定的。

为了说明,这里有一个示例图像展示了这一点(取自 W3.org):

在此处输入图像描述

由于line-heightis 20px,并且small元素具有font-sizeof 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-sizesmallp23pxfont-sizesmall6px

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值更改为:smalltop

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-height17px这将导致在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-size16px和所需的line-height值是20px,您将除以line-heightthefont-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>

于 2014-05-04T20:56:32.803 回答
1

Josh Crozier 发布的答案的替代方法是一起重置小行高:

p { line-height: 20px }
small {line-height: initial;}
<p>some normal-sized text</p>

<p>some <small>small</small>-sized text</p>

于 2017-02-13T20:51:56.907 回答
0

您可以使用相对值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>

于 2017-02-13T17:20:40.530 回答
0

发生这种情况是因为 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>

于 2017-02-16T07:57:53.440 回答