html - 如何使用 CSS 垂直居中文本?

我有一个 <div>包含文本的元素,我想对齐此 <div> 的内容垂直居中。

这是我的<div>风格:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

实现这一目标的最佳方法是什么?

最佳答案

你可以试试这个基本的方法:

div {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello World!
</div>

它只适用于单行文本,因为我们将行的高度设置为与包含框元素相同的高度。


更通用的方法

这是垂直对齐文本的另一种方法。此解决方案适用于单行和多行文本,但仍需要固定高度的容器:

div {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Hello World!</span>
</div>

CSS 只是调整 <div> 的大小, 垂直居中对齐 <span>通过设置 <div>的行高等于它的高度,并使 <span>带有 vertical-align: middle 的内联 block .然后它将 <span> 的行高设置为正常值。 ,所以它的内容会在 block 内自然流动。


模拟表格显示

还有一个选项,它可能不适用于旧的 browsers that don't support display: table and display: table-cell (基本上只是 Internet Explorer 7)。使用 CSS 我们模拟表格行为(因为表格支持垂直对齐),HTML 与第二个示例相同:

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}
<div>
  <span>Hello World!</span>
</div>


使用绝对定位

此技术使用绝对定位元素,将顶部、底部、左侧和右侧设置为 0。在 Smashing Magazine 中的一篇文章中进行了更详细的描述, Absolute Horizontal And Vertical Centering In CSS .

div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100%;
  border: 2px dashed #f69c55;
}
<div>
  <span>Hello World!</span>
</div>

https://stackoverflow.com/questions/8865458/

相关文章:

html - 如何使 div 不大于其内容?

html - HTML 中 id 属性的有效值是什么?

javascript - 如何在不重新加载页面的情况下修改 URL?

html - 如何使浏览器窗口的 div 高度为 100%?

javascript - 如何将一个元素移动到另一个元素中?

html - 使一个 div 填充剩余屏幕空间的高度

html - 如何创建一个类似于链接的 HTML 按钮?

php - 如何将 HTML 和 CSS 添加到 PDF 中

。使用哪个?">html -