Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical-align on h1 just won't work?

Tags:

html

css

I'm trying to align the text in a h1 vertically to the middle, seeing as the text might wrap it needs to look nice whether it's 1 line or 2.

This is the css I use:

h1 {
  font-size: 12pt;
  line-height: 10pt;
  min-height: 30px;
  vertical-align: middle;
}

The html is quite simply:

<h1>title</h1>

No matter what value I enter for vertical-align, the text is always at the top of the h1 element.

Am I miss-understanding the vertical-align property?

like image 770
Naatan Avatar asked Jul 23 '11 18:07

Naatan


People also ask

How do you vertically align h1 tags?

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

Why does Align Center doesn't work?

Short answer: your text isn't centered because the elements are floated, and floated elements "shrink" to the content, even if it's a block level element.

How do I fix vertical alignment in Word?

In the Page Setup group, select the Page Setup dialog launcher (which is located in the lower-right corner of the group). In the Page Setup dialog box, choose the Layout tab. In the Page section, select the Vertical alignment drop-down arrow and choose either Top, Center, Justified, or Bottom.


2 Answers

No CSS hacks needed. If I understand you correctly, then you can use this CSS:

h1 {
    font-size: 12pt;
    line-height: 10px;
    padding: 10px 0;
}

See demo fiddle which equals a minimum height of 30px;

A note about vertical-align: that style only works in conjunction with - and is calculated with regard to - the line-height style. So setting line-height at 10px, putting text with height 12pt leaves no space to align at all. But setting line-height to 30px would result in too much space between more lines of text. This shows a trick for vertical aligning several lines of text, but that is only needed when you have a fixed height container. In this case the container's height (the h1 element) is fluid, so you can use this simple padding solution.

like image 80
NGLN Avatar answered Nov 11 '22 15:11

NGLN


Center the H1 title using flexbox align items center and justify content center, see this example:

div {
padding: 1em;
border: 1px dashed purple;
}

h1 {
        display: flex;
        align-items: center;
        justify-content: center;
    }
<div>
<h1>Center this h1</h1>
</div>
like image 30
Andrey Tepaykin Avatar answered Nov 11 '22 15:11

Andrey Tepaykin