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>
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.
Just use padding top and bottom, it will automatically center the content vertically.
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.
The following solutions work for both single or multi-lined text.
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>
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>
<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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With