【问题标题】:CSS line height does not go all the way up or downCSS 行高不会一直向上或向下
【发布时间】:2021-07-05 08:45:16
【问题描述】:

我有一个困扰多年的问题。

带有line-height: 1 的文本会很紧凑,并且会到达周围元素的顶部和底部。

具有其他行高的文本将更具可读性,但同时,它将不再到达周围元素的顶部和底部。

这是问题的代码示例和 hackish 解决方案。更改行高或字体大小会破坏它。

这是一个可靠的解决方案吗?

.wrap {
  display: flex;
}

.first {
  background: red;
  width: 1rem;
}

.second,
.second2{
  line-height: 2;
}

.second2 {
  margin-top: -9px;
  margin-bottom: -7px;
}
<strong>Problem:</strong> The letter "A" does not align with the red top.<br><br>

<div class="wrap">
  <div class="first"></div>
  <div class="second">A text that<br>spans on multiple rows</div>
</div>

<br><br>

<strong>Hackish fix:</strong> The letter "A" does align with the red top.<br><br>

<div class="wrap">
  <div class="first"></div>
  <div class="second2">A text that<br>spans on multiple rows</div>
</div>

把line-height取到了极致,就是为了展示效果。

【问题讨论】:

  • 我怀疑是否有可靠的修复(相关:stackoverflow.com/a/62303653/8620333)。作为旁注,这是设计使然,那么为什么您要修复本应以这种方式工作的东西呢?
  • @TemaniAfif 如果您仍然需要行高,您还能如何让文本与框的顶部对齐?
  • 我在上面链接的解决方案。我没有看到更强大的。在所有情况下,您都需要有一个额外的属性来纠正这个差距。您可以通过引入 calc() 来优化它,使其更通用。
  • 我认为text-edge: text 有朝一日会支持更好的解决方案,但目前只能使用 hacky 解决方案。
  • @Alohci 好消息!这意味着我毕竟没有疯!

标签: css line-height


【解决方案1】:

正如你所观察到的,如果你给一个包含文本的元素:

  • font-size1em
  • line-height2em

文本将呈现在line-height的垂直中间。

文本仍将是 1em 高,但现在其上方和下方将有 0.5em 的空间。

为了(看似,但实际上不是)抵消这种垂直中间对齐,一种方法是应用一个

transform: translateY(-0.5em)

到包含文本的元素。


工作示例:

body {
  display: flex;
}

.wrap-1,
.wrap-2,
.wrap-3 {
  display: flex;
  margin-right: 12px;
}

.first {
  background: red;
  width: 1rem;
}

.wrap-1 .second {
  font-size: 1em;
  line-height: 1em;
  background-color: rgb(255, 255, 0);
}

.wrap-2 .second {
  font-size: 1em;
  line-height: 2em;
  background-color: rgb(255, 255, 0);
}

.wrap-3 .second {
  font-size: 1em;
  line-height: 2em;
  background-color: rgb(255, 255, 0);
}

.wrap-3 .second p {
  background-color: rgba(0, 0, 0, 0.2);
  transform: translateY(-0.5em);
}

p {
  margin: 0;
  padding: 0;
  background-color: rgba(0, 0, 0, 0.2);
}
<div class="wrap-1">
  <div class="first"></div>
  <div class="second"><p>A text that<br>spans on multiple rows</p></div>
</div>

<div class="wrap-2">
  <div class="first"></div>
  <div class="second"><p>A text that<br>spans on multiple rows</p></div>
</div>

<div class="wrap-3">
  <div class="first"></div>
  <div class="second"><p>A text that<br>spans on multiple rows</p></div>
</div>

【讨论】:

  • 是的,我认为您已经完成了一半以上。我不使用em,而只是一个数字。我现在已经读到,在这种情况下,数字 2 是字体大小乘以 2,所以如果字体大小是 1rem,它将是 2 * 1rem。我的猜测是,一个 calc 函数可以做到这一点。
  • calc() 听起来是个好主意。如果将calc()CSS Custom Property 或两个结合使用,您可能会做得更多。
  • 是的,字体大小的自定义属性以防止重复。
猜你喜欢
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 2021-09-01
  • 2023-02-24
  • 1970-01-01
  • 2020-01-14
相关资源
最近更新 更多