5

How can I vertically center some simple text in a normal <div>? I have markup like this:

<div style="height:200px;">
   <span style="display:inline; vertical-align:middle;">ABOUT</span>
<div>

It doesn't work under either Firefox or Internet Explorer. Why not?

Ry-
  • 209,133
  • 54
  • 439
  • 449
Jacek
  • 11,107
  • 22
  • 62
  • 116
  • It doesn't work under Chrome either. Because that's not how `vertical-align` works. – Roddy of the Frozen Peas Aug 28 '12 at 18:02
  • possible duplicate of [How to align text vertically center in div with css?](http://stackoverflow.com/questions/8865458/how-to-align-text-vertically-center-in-div-with-css) – user Mar 09 '14 at 18:03

2 Answers2

10

That's not what vertical-align does. You probably want line-height:

<div>
    <span style="line-height: 200px;">ABOUT</span>
</div>

Here's a demo.

Ry-
  • 209,133
  • 54
  • 439
  • 449
1

I have found using a spacing element to the most reliable method of centering any element you know the height of (image, text). This will center an element in a container of any height.

CSS:

#outer {
    background: grey;
    height: 200px; /* any height */
}

#outer > div {
    height: 50%;
    margin-bottom: -6px;
}

#outer span {
    font-size: 12px;
}

HTML:

<div id="outer">
    <div></div>
    <span>Example</span>
</div>
Vukašin Manojlović
  • 2,555
  • 2
  • 20
  • 26
MaxPRafferty
  • 4,611
  • 4
  • 29
  • 38
  • May as well use relative or absolute positioning in such cases. – Ry- Aug 28 '12 at 18:23
  • Actually, with an absolutely positioned element inside a relatively positioned one, using, say, top:50%, your element will not be perfectly centered because you cannot subtract the element's own height. For dynamic vertical centering you need a negative padding or margin. – MaxPRafferty Aug 28 '12 at 18:30
  • `top: 50%; margin-top: -(half height)`, actually. – Ry- Aug 28 '12 at 18:35
  • Well I'll be darned: http://jsfiddle.net/MaxPRafferty/2VHBZ/13/ also, thanks for catching me using the full element height! – MaxPRafferty Aug 28 '12 at 18:44