如何在标题中垂直居中文本?

Pat*_*rio 7 html css css3

我有一个<h1>宽度和高度设置的元素.我想将文本垂直居中,但我似乎无法做到.文本可以是单行或多行.请参阅下面的代码:

h1 {
  width: 150px;
  height: 150px;
  background-color: #888;
  color: white;
  text-align: center;
  vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Test</h1>
Run Code Online (Sandbox Code Playgroud)

Sti*_*ers 15

以下解决方案适用于单行或多行文本.

1. Flexbox:

h1 {
  width: 200px;
  height: 200px;
  margin: 0;
  background-color: gray;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<h1>A quick brown fox</h1>
Run Code Online (Sandbox Code Playgroud)

2. CSS表格单元格:

h1 {
  width: 200px;
  height: 200px;
  margin: 0;
  background-color: gray;
  color: white;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<h1>A quick brown fox</h1>
Run Code Online (Sandbox Code Playgroud)

3.线高(+ <span>):

h1 {
  width: 200px;
  height: 200px;
  margin: 0;
  background-color: gray;
  color: white;
  text-align: center;
  line-height: 200px;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;      
}
Run Code Online (Sandbox Code Playgroud)
<h1><span>A quick brown fox</span></h1>
Run Code Online (Sandbox Code Playgroud)


Jac*_*ray 5

如果只有一行文本,只需将其设置line-height为150px:

h1 {
  width: 150px;
  height: 150px;
  line-height: 150px;
  background-color: #888888;
  color: white;
  text-align: center;
  vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Test</h1>
Run Code Online (Sandbox Code Playgroud)

但是,这仅在文本未换行时才有效.如果是,您可以使用flexbox将其居中:

h1 {
  width: 150px;
  height: 150px;
  
  display: flex;
  align-items: center;
  justify-content: center;
  
  background-color: #888888;
  color: white;
  text-align:center;
  vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)
<h1>Super Monkey!</h1>
Run Code Online (Sandbox Code Playgroud)