Html 如何垂直居中文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43807232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:38:14  来源:igfitidea点击:

How do I vertically center text?

htmlcss

提问by Petey

I've been working on getting the text in my content div centered vertically and I'm stumped. The container includes 1 div with a title and 1 div with content.

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

I've tried elements such as:

我尝试过以下元素:

vertical-align: middle;

and also playing with the displays/positioning, but I'm not having any luck.

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

The current CSS is the following:

当前的 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;
}

回答by Paolo Forgia

Flexbox

弹性盒

Flexboxallows you to vertically align the text without having a divwith a fixed height. It is now supported by all the modern browsers.

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

Check my other answerto see all the problems and workarounds for Flexbox. The majority are for Internet Explorer.

检查我的其他答案以查看 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

line-height

If you know the heightof the external div, you can use line-height.

如果你知道height外部的div,你可以使用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

display: table-cellis another good alternative which allows you to vertically align without knowing the height of the div. It works in older browsers too (except Internet Explorer 7).

display: table-cell是另一个不错的选择,它允许您在不知道div. 它也适用于较旧的浏览器(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>