2

我有一个多年来一直存在的问题。

文本line-height: 1将是紧凑的,并将到达周围元素的顶部和底部。

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

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

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

.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取到了极致,就是为了展示效果。

4

1 回答 1

1

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

  • 一个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>

于 2021-04-09T13:27:40.533 回答