Vertical text alignment – CSS _ and # hacks!

To align text inside <div> or other elements.

The CSS standard is just

.alignStyle{

vertical-align: middle;

}

But this won’t work with IE.

That’s why I am learning those complicated HACKS!

Great Job, Bill, just great…

There are two hacks avaiable, underscore and sharp[]

Learn this hacks if your are paranoid like me.

use <table> when it is really a table but not for layout.

IDEAS of _ and # hacks

  1. The underscore (“_”) is allowed in CSS identifiers by the CSS2.1 Specification
  2. CSS2 selector #value[id] is equivalent to selector #value, but Internet Explorer ignores these types of selectors. 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 (similarly works .value[class])

Example

  1. #box {
    min-height: 300px; //interpret by other browsers
    height: auto;
    _height: 300px; //only IE interpret
    }
  2. #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;} */

Vertical align code sample

CSS:

#outer {height: 400px; overflow: hidden; position: relative; border:1px solid #0000FF; width:500px;}
#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%}

HTML:

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

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s