How to vertically center text in a div using CSS

February 27th, 2010

How to vertically center text in a div using CSS

CSS

It’s pretty easy to center text in a div using CSS…horizontally that is. But what about when you try to use CSS to center text vertically? Just a bit tricky, huh? The trusty “vertical-align:middle” CSS method works wonders in a table td, but somehow fails you when you try it in a div. And you don’t want to have to resort to using a table JUST to vertically center text. Here’s the CSS solution that lets you vertically center text in a div.

(This solution only works if the text being vertically centered is a single line.)

Start with your basic div:

This is text inside a div.

<!DOCTYPE html>
<html>
<head>
<title>How to Create Transparency with CSS</title>
<style type=”text/css”>
div {width:300px; height:100px; background-color:#93b51b; color:#ffffff; border:1px solid #000000;}
</style>
</head>
<body>
<div>This is text inside a div.</div>
</body>
</html>

Let’s start the pretty-ing process by first centering the text horizontally:

This is text inside a div.

<style type=”text/css”>
div {width:300px; height:100px; background-color:#93b51b; color:#ffffff; border:1px solid #000000; text-align:center}
</style>

Next, wrap the text in a paragraph (that’s our secret weapon):

<body>
<div><p>This is text inside a div.</p></div>
</body>

And finally, style the paragraph (this is where the magic occurs):

<style type=”text/css”>
div {width:300px; height:100px; background-color:#93b51b; color:#ffffff; border:1px solid #000000; text-align:center}
p {margin:0; line-height:100px;}
</style>

This is text inside a div.

Our final code looks like this:

<!DOCTYPE html>
<html>
<head>
<title>How to Create Transparency with CSS</title>
<style type=”text/css”>
div {width:300px; height:100px; background-color:#93b51b; color:#ffffff; border:1px solid #000000; text-align:center}
p {margin:0; line-height:100px;}
</style>
</head>
<body>
<div><p>This is text inside a div.</p></div>
</body>
</html>

     Add to Delicious


comments...

  1. Leels says:

    I have to admit, I always end up using a table instead. This makes it so much easier.



leave a comment...

Spam Protection by WP-SpamFree



Category: All Categories, CSS, Design Stuff Follow any responses to this post through the RSS 2.0 feed or trackback from your own site.

Tags: , , , , ,