CSS行高不完全向上或向下。

3

多年来我一直有一个问题。

使用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>

这里的行高被极端地设置,只是为了展示效果。


我怀疑是否有一个可靠的解决方法(相关链接:https://dev59.com/8k0GtIcB2Jgan1znzaNX#62303653)。顺便说一下,这是按设计来的,所以为什么要修复本来就应该正常工作的东西呢? - undefined
@TemaniAfif 如果你仍然想要保留行高,又希望文本与盒子顶部对齐,还有其他方法吗? - undefined
1
我在上面提供的解决方案中没有看到更强大的选项。在所有情况下,您需要添加一个额外的属性来修复这个问题。您可以尝试使用calc()函数来使其更通用化,从而实现优化。 - undefined
1
我认为text-edge: text将来会支持更好的解决方案,但目前只有这个折中的解决方案可用。 - undefined
@Alohci 太好了!这意味着我终于不再是个疯子了! - undefined
1个回答

2

如您所见,如果给一个包含文本的元素:

  • font-size 设置为 1em
  • line-height 设置为 2em

文本将在 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>


1
是的,我认为你已经完成了一大半。我不使用em,而是直接使用数字。我现在了解到,在这种情况下,数字2是字体大小乘以2,所以如果字体大小是1rem,那么就是2 * 1rem。我猜测使用calc函数应该可以解决问题。 - undefined
1
calc()听起来是个不错的主意。如果你将calc()与一个或两个CSS自定义属性结合起来,可能还能做得更多。 - undefined
1
是的,自定义属性用于防止字体大小重复。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接