Contact Us


FriendFeed FriendFeed


follow us on twitter Twitter


 Rss Feed


Favorites Add to Favorites

Thursday, July 9, 2009

Vertical align text in floating div using css

Do you know how to vertically align a text in a floating div? When a content is dynamically generated and you want to align it automatically according to it?

Today i was experimenting about this for a long time and finally i have got a solution which will work in all the browsers including ie6. There are many ways of doing it, but i would like to work the code in all the majore browsers inculding ie6.

So here is the code...

<div class="contentdiv">
<p>It works! Vertically Center Align!</p>

.contentdiv{ width: 135px; height: 84px; display: table; border:2px solid red;}
.contentdiv p{ display: table-cell; vertical-align: middle; text-align: center;}

Hack for ie:
.contentdiv p{*margin-top: expression(this.offsetHeight < this.parentNode.offsetHeight ? parseInt((this.parentNode.offsetHeight - this.offsetHeight) / 2) + "px" : "0");}

According to the height you increase, the content will get vertically aligned center. My only worry is iam using expression. We must try to avoid using more expression. But it looks very simple. Fine, any other method of handle this will be a great help! Please feel free to post.

Labels: , , ,


Anonymous Anonymous said...

I tested this in IE 7 and it didn't work...

September 10, 2009 at 1:39:00 PM PDT  
Anonymous Les said...

It works in firefox and IE7

September 28, 2009 at 12:51:00 AM PDT  
Anonymous gav said...

Hey man, i tested this with the following o/s browsers and it works fine..

PC Vista Fx3.5
PC Vista IE8
PC Vista IE7
PC Vista Chrome 3
PC Vista Opera 10
PC Vista Safari 4
MAC Safari 3

October 21, 2009 at 7:14:00 PM PDT  
Blogger Madhu said...

For IE 7

*+html .contentdiv {}

April 5, 2010 at 8:50:00 PM PDT  
Anonymous Anonymous said...

Use this simple example. It shows you how to do it whether in a div or a list. And it doesn't use line heights, javascript or expressions =

May 10, 2010 at 3:20:00 AM PDT  
Anonymous Anonymous said...

Do you know how to vertically align a text in a floating div?

Where's the float?

January 21, 2014 at 8:56:00 PM PST  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home