【问题标题】:How do I vertically center text? [duplicate]如何垂直居中文本? [复制]
【发布时间】:2017-10-04 01:41:31
【问题描述】:

我一直在努力让我的内容 div 中的文本垂直居中,但我很难过。该容器包括 1 个带标题的 div 和 1 个带内容的 div。

我尝试过以下元素:

vertical-align: middle;

并且还玩显示/定位,但我没有任何运气。

当前的 CSS 如下:

.content-wrapper {
  height: 100vh;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: left;
  text-align: left;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  color: #000;
  font-family: Montserrat;
  text-transform: none;
  -webkit-transform: translateY(40vh);
  transform: translateY(40vh);
  will-change: transform;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
  transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
  padding-top: 10%;
  padding-right: 25px;
  padding-left: 30px;
  float: right;
  width: 35%;
  background-color: #f0f7fc;
}

【问题讨论】:

  • flex 版本将内容垂直居中,但也将其水平居中。我需要在垂直居中的容器中左对齐文本。
  • 如果您使用 flex,那么为什么不看看属性的含义以便您了解它是如何工作的,您可以轻松地将文本垂直居中并左对齐

标签: html css


【解决方案1】:

弹性盒

Flexbox 允许您垂直对齐文本,而无需使用固定的divheight。现在所有现代浏览器都支持它。

Check my other answer 查看 Flexbox 的所有问题和解决方法。大多数用于 Internet Explorer。

display: flex;
align-items: center;

div {
  width: 50px;
  height: 100px;
  display: flex;
  align-items: center;
  border: 1px solid black;
}
<div>
  Test
</div>

line-height

如果知道外部divheight,可以使用line-height

height: 100px;
line-height: 100px; /* same value as height */

div {
  width: 50px;
  height: 100px;
  line-height: 100px;
  border: 1px solid black;
}
<div>
  Test
</div>

display: table-cell

display: table-cell 是另一个不错的选择,它允许您在不知道div 的高度的情况下垂直对齐。它也适用于旧版浏览器 (except Internet Explorer 7)。

display: table-cell;
vertical-align: middle;

div {
  width: 50px;
  height: 100px;
  display: table-cell;
  vertical-align: middle;
  border: 1px solid black;
}
<div>
  Test
</div>

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 2018-07-15
    • 2013-02-15
    • 2012-02-10
    • 2021-09-04
    • 2013-10-15
    相关资源
    最近更新 更多