如何垂直居中文字?

Pet*_*tey 8 html css css3

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

我尝试过如下元素:

vertical-align: middle;
Run Code Online (Sandbox Code Playgroud)

并且还玩显示器/定位,但我没有运气.

目前的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;
}
Run Code Online (Sandbox Code Playgroud)

Pao*_*gia 27

Flexbox的

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

查看我的其他答案,查看Flexbox的所有问题和解决方法.大多数是Internet Explorer.

display: flex;
align-items: center;
Run Code Online (Sandbox Code Playgroud)

div {
  width: 50px;
  height: 100px;
  display: flex;
  align-items: center;
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  Test
</div>
Run Code Online (Sandbox Code Playgroud)

line-height

如果你知道height外部的div,你可以使用line-height.

height: 100px;
line-height: 100px; /* same value as height */
Run Code Online (Sandbox Code Playgroud)

div {
  width: 50px;
  height: 100px;
  line-height: 100px;
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  Test
</div>
Run Code Online (Sandbox Code Playgroud)

display: table-cell

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

display: table-cell;
vertical-align: middle;
Run Code Online (Sandbox Code Playgroud)

div {
  width: 50px;
  height: 100px;
  display: table-cell;
  vertical-align: middle;
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  Test
</div>
Run Code Online (Sandbox Code Playgroud)