Web Design Blog

This is where we store some of our Web Development thoughts, tips and tricks, just because we like to share.

Centering Text Vertically With CSS

CSS can be extremely odd some times, and vertically centralizing text in CSS is one of those occasions which makes me think that…

Centering text horizontally within a div is extremely straight forward. All you need to to do is use the text-align:center property. But for some reason, there isn’t an easy remedy to centralize text vertically with CSS. It’s easily accomplished with tables, but as web development has progressed, the use of tables is now frowned upon by the web geeks (unless you’re displaying tabular data).

Admittedly, aligning text vertically central is not a feature I require a lot of the times, but I do need it now and then. For instance, I needed it this morning…

Example for centering text vertically

Below is an image of a navigation bar. I’ve added the border just for visual ease (it’s not part of the design). Ideally, i’d like the “360-degree feedback” link vertically central with in its container, so it’s not floating at the top, touching the border.

Centering Text Vertically With CSS

Like this…

Centering Text Vertically With CSS

The Solution

Here’s the code I used- I’ve tested it in I.E 6/7 and Firefox 2/3.

/* dark blue ---*/

#contentleft_btnsdarkblue{
background:url('images/button4.jpg') left no-repeat;
padding-left:35px;
height:60px;
display: table;
#position: relative;
overflow: hidden;
}

#contentleft_btnsdarkblue a{
color:#004064;
}

/* light blue ---*/

#contentleft_btnslightblue{
background:url('images/button1.jpg') left no-repeat;
padding-left:35px;
height:60px;
display: table;
#position: relative;
overflow: hidden;
width:160px;
}

#contentleft_btnslightblue a{
color:#009FE0;
}

.contentleft_btntxt{
#position: relative;
#top: -50%
}

.contentleft_vertical{
#position: absolute;
#top: 50%;display:
table-cell;
vertical-align: middle;
width:160px;
}

[/pre]

For ease, you can download the Centering Text Vertically With CSS code.

15 Sep 2008 / 0 Comments / CSS Tips & Tricks / by Maruf

Leave a Reply

© 2012 BrightCherry :)