Vertical centring text with CSS
CSS is is awesome, in comparison to table based layouts. However, some simple table things are difficult in CSS, such as vertical centring text. But don't go getting table-ly, it can still be done!
Known text
If you know the text to be centred, it is rather easy. You have two options.
<style type="text/css">
#container {
padding: 10px 0;
}
</style>
<div id="container">
Example of some lovely<br />
multiline text.
</div>You can use CSS's padding to add padding top and bottom, to make the text appear in the middle. This is useful for multiline text.
<style type="text/css">
#container {
height: 100px;
line-height: 100px;
}
</style>
<div id="container">
Example
</div>You can exploit the line-height property to make the text vertically centred. This only works with one line of text. You can guess what happens if there is more than 1.
Dynamic multiline text
Here is where things start to get somewhat tricky, and may have you crying for tables.
<style type="text/css">
#container {
display: table-cell;
vertical-align: middle;
}
</style>
<div id="container">
<?php echo $content; ?>
</div>Easy huh? Of course it could never be that easy, as long as IE 6 + 7 have market share. There is a ugly (albeit neccesary) workaround for those lovely IE versions.
CSS is fun!
Yep, it's another one of those learn how to do it right, then learn the IE compatible version CSS things! Good luck folks!
Comments
rakesh juyal
Posted on Monday, 4th October 2010 @ 6:36pm.Of course it could never be that easy, as long as IE 6 7 have market share
:D
Leave a Comment
Note: Your comment may require approval before it is posted to the site.