How do I center text vertically?

Hello. I’m trying to center an h1 in a div vertically so that it’s in the center on the y axis. How would I do this? Here’s my code:

#title {
    font-family: 'Raleway', sans-serif;
    text-align: center;
    color: darkorange;

~ @shanecode9

The simplest way I know of is to use line-height with the value set to the height of the view-port space the H1 occupies.

If there’s a small difference in height between the the div and h1, using the same value for padding on top and bottom is a quick, easy option. Without flex-box, you can use margin and positioning and transform css properties or flexbox with align-items: center;.

Flexbox is easier.

I’m not a fan of padding and prefer line-height if there is no additional support such as flexbox or grids.

I hadn’t realized line-height could be used that way, until you said so. Does it work for elements that occupy more than one line?

1 Like

It is not very adaptive once the view-port changes size when it can render in a less than appreciable way. Best use it for short headings and button labels, table headings, &c.

I use the word ‘adaptive’ to predate responsive design and mobile devices. There was a smaller range of view-ports to deal with, and all or most were CRTs. The goal then was to have our layouts fit into the display constraints bounded by 480x320 thru 1024x768.

In those days CSS was a lifesaver but we still didn’t have media queries; hence not ‘responsive design’ capable. The best we could do was make our layouts adaptive, meaning able to adapt to narrow or wide.

Now that we do have media queries you can stretch the viable limits of multi-line usage of line-height. It is possible within certain view-port sizes to leverage this technique and not use padding.

1 Like

Okay, maybe we did have responsive capability, but only through DOM script. It was the only way we could get the viewport dimensions. That is the genesis of responsive design which goodies were given over to the CSS realm to lessen the workload on programmers. CSS3 is very well thought out and every web developer working in league with graphics designers will do well to exploit it at every turn.

How would I do it so that my text would be in the middle of my div on different sized devices?

Use media queries to resolve relative sizes (rem, em) for each dimension range.