scriptygoddess

09 Jan, 2007

Vertical Center Text in DIV

Posted by: Jennifer In: Bookmarks|CSS|CSS related

Like I said, I'm still fighting my way through understanding CSS. Here's a little tid-bit I finally understand today. Had a bit of text that I wanted to have centered in a nav bar. "vertical-align: middle;" didn't seem to do anything. Found this article which said this:

the thing with vertical-align is that it's vertical aligning text according to the default line-height of the inline-text boxes. You can manipulate that by setting the line-height to the same height as your block, but this will only be effective if the line of text (link) does not wrap onto more than one line.

NOW it makes sense…

So if you had:

<div id="nav"><a href="#" class="centerme">Home</a></div>

Then:

#nav {
height: 25px;
line-height: 25px;
}
.centerme {
vertical-align: middle;
}

should do the trick…

4 Responses to "Vertical Center Text in DIV"

1 | GeminiGeek

January 11th, 2007 at 12:27 am

Avatar

It works with or without vertical-align, as long as height=line-height. Vertical-align somehow only works if there's images, like this hack.

2 | Benny

January 15th, 2010 at 4:32 pm

Avatar

Thank you. I have been googling this solution forever it feels like. Finally it all makes sense to me.

3 | Kuldeep

April 6th, 2011 at 4:59 am

Avatar

This will work for one line only if the text is of more than one line than it will create bug.

4 | Jennifer

April 6th, 2011 at 12:55 pm

Avatar

Correct. This only works with one line of text. There are a few ways to handle it with two lines (extra divs, moving the text down via -margins etc…) To be honest, that's the point where I start to weigh the value of extra markup and css vs. a simple single table cell set to center it's content… :)

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements