Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text vertically in a heading?

Tags:

html

css

I have an <h1> element that has width and height set. I want to vertically center the text in it, but I can't seem to do it. The text can be either single or multi-lined. Please see my code below:

h1 {
  width: 150px;
  height: 150px;
  background-color: #888;
  color: white;
  text-align: center;
  vertical-align: middle;
}
<h1>Test</h1>
like image 642
Patrick Gregorio Avatar asked Jun 22 '16 15:06

Patrick Gregorio


People also ask

How do I center text vertically in a label?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center.

How do I center my h1 vertically?

Just use padding top and bottom, it will automatically center the content vertically.

How do you center text in header?

To set the heading alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <h1> to <h6> tag, with the CSS property text-align.


2 Answers

The following solutions work for both single or multi-lined text.

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;
}
<h1>A quick brown fox</h1>

2. CSS table-cell:

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

3. Line height (+<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;      
}
<h1><span>A quick brown fox</span></h1>
like image 54
Stickers Avatar answered Oct 18 '22 14:10

Stickers


If there is only one line of text, just set the line-height to 150px:

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

However, this will only work if the text doesn't wrap. If it does, you can use flexbox to center it:

h1 {
  width: 150px;
  height: 150px;
  
  display: flex;
  align-items: center;
  justify-content: center;
  
  background-color: #888888;
  color: white;
  text-align:center;
  vertical-align: middle;
}
<h1>Super Monkey!</h1>
like image 42
Jacob Gray Avatar answered Oct 18 '22 14:10

Jacob Gray