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...
HTML:
<div class="contentdiv">
<p>It works! Vertically Center Align!</p>
</div>
CSS:
.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.
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...
HTML:
<div class="contentdiv">
<p>It works! Vertically Center Align!</p>
</div>
CSS:
.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: CSS, div min height, float, vertical align text
FriendFeed
Twitter
Add to Favorites


5 Comments:
I tested this in IE 7 and it didn't work...
It works in firefox and IE7
Thanks
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
PC XP IE6
PC XP Fx2
MAC Fx2
MAC Safari 3
For IE 7
*+html .contentdiv {}
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 = http://www.andy-howard.com/verticalAndHorizontalAlignment/index.html
Post a Comment
Subscribe to Post Comments [Atom]
<< Home