将标题线(文本顶部)与不同大小的字体对齐

Align the capline (top of text) with different size fonts

我在网页上有一组编号的小节,每个小节都有一个与该节的序号(编号)一致的关联标题。它本质上是一个有序列表,其中每个项目都包含任意内容。

设计要求 (a) 每个部分的序号大约是标题文本的两倍高,(b) 标题(呈现为 FULLCAPS)的首线(顶部)与首线对齐序数。

标题文本是动态的,可能会占用 1-4 "lines" 的任意位置,具体取决于长度。

我尝试在使用 table-cell 格式化的元素中使用 vertical-align:top,它非常接近所需的外观:

.title_line {
  display: table;
}
.title_line .ordinal {
  display: table-cell;
  vertical-align: top;
  font-size: 4em;
}
.title_line .title {
  display: table-cell;
  vertical-align: top;
  font-size: 2em;
  text-transform: uppercase;
}
<body>
  <div class="title_line">
    <div class="ordinal">3</div>
    <div class="title">The capline (top) of this text should be aligned with the top of the ordinal.</div>
  </div>
</body>

但与标题文本相比,序号上方的垂直间隙存在明显差异。

有什么方法可以为不同大小的文本指定首行对齐方式吗?

这可以通过设置 1emline-height 来解决。

.title_line {
    display: table;
}

.title_line .ordinal {
    vertical-align: top;
    display: table-cell;
    line-height: 1em;
    font-size: 4em;
}

.title_line .title {
    display: table-cell;
    vertical-align: top;
    font-size: 2em;
    text-transform: uppercase;
}
<body>
  <div class="title_line">
    <div class="ordinal">3</div>
    <div class="title">The capline (top) of this text should be aligned with the top of the ordinal.</div>
  </div>
</body>

这有效地消除了实际字体和呈现方式之间的 space。如果您为 .ordinal 添加轮廓或背景,您可以看到它是如何工作的:

span {
  vertical-align: top;
  font-size: 4em;
  outline: 1px solid red;
}
.fix {
  line-height: 1em;
}
<span>3</span>
<span class="fix">3</span>