Patrick Gregorio Patrick Gregorio - 5 months ago 12
CSS Question

How to center text vertically in a H1 tag?

I have an

h1
element that has a width and height. I want to vertically center the text but I can't seem to do it. Please see my code below:

Fiddle



h1 {
width: 150px;
height: 150px;
background-color: #888888;
color: white;
text-align: center;
vertical-align: middle;
}

<h1>Test</h1>




Answer

I suggest to use flexbox.

h1 {
  width: 150px;
  height: 150px;
  background-color: #888888;
  color: white;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
<h1>Test</h1>

It also works when the text wraps.

h1 {
  width: 150px;
  height: 150px;
  background-color: #888888;
  color: white;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
<h1>Test Test Test</h1>

Or, to use CSS table cell.

h1 {
  width: 150px;
  height: 150px;
  background-color: #888888;
  color: white;
  text-align: center;
  vertical-align: middle;
  display: table-cell;
}
<h1>Test Test Test</h1>

Or, to use the line height trick, note added a span tag in h1.

h1 {
  width: 150px;
  height: 150px;
  background-color: #888888;
  color: white;
  text-align: center;
  line-height: 150px;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;      
}
<h1><span>Test Test Test</span></h1>