0

如您所知,我们可以使用line-height具有等于height容器属性的值的属性来垂直居中该容器内的单行:

.container {
  width: 300px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  outline: 1px solid red;
}
<div class="container">
  <p>This is some text.</p>
</div>

我在很多参考资料中都看到过这种方法,例如:

现在的问题是,为什么要height设置属性?是否有必要,或者我们可以简单地管理line-height吗?

4

1 回答 1

0

如果存在单个文本,则您的 line-height 将足以使文本垂直居中。这是因为,即使存在 1 条单行,等于 200px,也会自动将 min-height 设置为 200px。

.container {
  width: 300px;
  line-height: 200px;
  text-align: center;
  outline: 1px solid red;
}
<div class="container">
  <p>This is some text.</p>
</div>

现在,让我们看看没有文本的例子。

在这里,在这种情况下,您的 line-height 不起作用,因为没有文本存在。在这种情况下,您height:200px会派上用场,因为仍然没有文本,即使没有任何内容,它也会提供至少 200px 的高度(所以在这里,如果您想要一些高度始终存在,即使没有任何数据,height:200px也会是有用)。

.container {
  width: 300px;
  line-height: 200px;
  text-align: center;
  outline: 1px solid red;
}
<div class="container">
  <p></p>
</div>

于 2021-12-27T08:45:17.817 回答