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

标签 html css vertical-alignment

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

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

标题文本是动态的,根据长度可能会占用 1-4“行”。

我尝试在使用 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>

enter image description here

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

有没有办法为不同大小的文本指定大写对齐方式?

最佳答案

这可以通过将 line-height 设置为 1em 来解决。

.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>

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

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

关于html - 将标题线(文本顶部)与不同大小的字体对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35050340/

相关文章:

Css - 如何覆盖表格单元格的 css

html - 使图像缩放并保持在 div 的中间

html - 在 CSS 中,如何制作一条垂直居中的线,它占据 block 元素后剩余的水平空间?

javascript - 在 webGL 中绘制参数形状(不使用 Three.js)

javascript - 在浏览器上推迟脚本和执行顺序

javascript - 我的立方体消失了,我不知道为什么

javascript - 从 html5 应用程序打开 pdf 的外部链接 - PhoneGap

css - 缩略图未排列

html - jQuery UI 嵌套列表

html - 将一些 margin-top 强制为 2 个内联 block 元素之一