用什么? "vertical-align:top" 或 "vertical-align:text-top"

What to use? "vertical-align:top" or "vertical-align:text-top"

这两个属性是一样的还是有不同的用法? vertical-align:topvertical-align:text-top

vertical-align:top :- This will align the top of element with the top of tallest element.

vertical-align:text-top :- This will align the top of element the top of the parent element's font

大多数情况几乎相同,因为您的字体和文本都相同。当您的行包含一些其他元素(例如图像和文本)时,它会产生不同的影响,这种情况 text-top 将使您的元素与 tallest text 对齐,即使图像比文本高,但 top 将对齐它与 top of imagewho ever is tallest in line whether text or image.

差异可以通过 line-height 属性.

来解释

MDN Source

text-top Aligns the top of the element with the top of the parent element's font.

top Align the top of the element and its descendants with the top of the entire line.

.top {
  line-height: 5em;
}

.text-top {
  line-height: 5em;
}

.top span {
  vertical-align: top;
}
.text-top span {
  vertical-align: text-top;
}
<div class="top">I am vertical-align: <span>top</span>
</div>
<div class="text-top">I am vertical-align: <span>text-top</span>
</div>

注意上面的例子,要放在上面的时候,text-top在下面。

因为我们设置了line-height: 5emem 是相对于字体大小的。根据定义,text-top 将与父元素(.text-top)的基线对齐。

尽管它们之间存在细微差别,但是 "vertical-align" 属性 的这两个属性在某些文本格式化时可能会非常方便。您可能会这样理解:vertical-align 属性 是自我描述的,有助于对齐元素 垂直于行框高度。现在 vertical-align:top ,将元素的上边缘与行框的上边缘对齐。 而 vertical-align:text-top 将元素的上边缘与行框的文本框的上边缘对齐。