A friend of mine runs a small online hardware store and is working on a new site. He often asks me questions about this-and-that. This morning he had a question that required me to do some investigation.

"How do I vertically center a block of text inside a <div> tag?"

I did some googling and found a couple of interesting hacks and solutions. The one I liked the most came from a chap called Dušan Janovský. I'll sum it up here.

There are several ways we can achieve vertical centering. Obviously, it is important that the chosen method provides compatibility between browsers (IE is notorious for its lacking - or at least, "different" -  CSS support).

To define the actual problem:
  • We are working inside an area with a known height on the page (eg, a <div>)
  • We wish to place an object inside the <div> and center it vertically. We do not, beforehand, know the height of the object (the height of a block of text depends on people's browser settings etc.)
  • HTML Tables is definitely a no-no
Mr. Janovský goes through an example on his page but I'll just show you his conclusion here.

Time for some code!

  <title>Universal vertical center with CSS</title>

  <style type="text/css">
   #outer {height: 400px; overflow: hidden;
position: relative;}
#outer[id] {display: table; position: static;}

#middle {position: absolute; top: 50%;}/* for explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; position: static;}

#inner {position: relative; top: -50%}/* for explorer only */
/* optional: #inner[id] {position: static;} */



<div id="

  <div id="middle">
    <div id="
      any text
      any height
      any content, for example generated from DB
      everything is vertically centered



Color legend:

CSS style for Internet Explorer only
CSS styles for standard browsers

The CSS2 selector#value[id] is equivalent to selector #value. Luckily, Internet Explorer ignores anything it doesn't understand. Generally: syntax *[foo] means any element with attribute foo. Any HTML element #something must have the attribute id set to "something".

That's the trick -- #value[id] works in standard browsers only (.value[class] also works)

There's a CSS property position set to absolute or relative for Internet Explorer. The code position: static get's it back to default value in standard browsers (the "top" property doesn't work then).

You can read the entire article on Dušan Janovský's page.

comments powered by Disqus