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

时间:2016-01-27 23:42:02

标签: html css css3 vertical-alignment

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

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

标题文字是动态的,可能占用1-4和#34;行"视长度而定。

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



.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>
&#13;
&#13;
&#13;

enter image description here

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

有没有办法为不同大小的文字指定上限对齐?

1 个答案:

答案 0 :(得分:5)

可以通过设置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; }来修复此问题。

&#13;
&#13;
<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>
&#13;
.ordinal
&#13;
&#13;
&#13;

这有效地消除了实际字体与其呈现方式之间的空间。如果您向span { vertical-align: top; font-size: 4em; outline: 1px solid red; } .fix { line-height: 1em; }添加大纲或背景,则可以看到其工作原理:

&#13;
&#13;
<span>3</span>
<span class="fix">3</span>
&#13;
x
&#13;
&#13;
&#13;