I know about the the text-align:center property, but how does one vertically center text?

3 answers

This was chosen as the best answer

Much depends on your application, but you can vertically center a single line of text in an element by setting the line-height to match the height of the element.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
            <style type="text/css" media="screen">

                height: 100px;
                background-color: #ccc;

            div#header h2{
                line-height: 100px; 
                background-color: #333; 
                margin: 0 auto; 
                width: 80%; 
                text-align: center;

        <div id="header">
            <h2>Centered heading</h2>

see: http://www.boldfishclient.co.uk/doctype/STr/

Answered over 8 years ago by Tony Crockford

vertical-align: middle is the CSS property for it. I.E.:

div { vertical-align: middle; }

Mind you, this won't vertically align boxes -- just text, unfortunately that requires some trickery with display: table-cell and fixed heights.

Answered over 8 years ago by Nathan DeGruchy

The above examples are the most friendly ones. You could however also use absolute positioning, like so:

h2 {
  position: absolute;
  top: 50%;
  left: 50%;  
  width: 300px;
  height: 200px;
  margin: -100px 0 0 -150px;

This might not be the right way to go as the headline needs to have a fixed dimensions and will be clipped if you shrink the browser window much. But I'm just giving you the option. :)

Answered over 8 years ago by Jens Hedqvist