Main content begins here

Vertical Centering of Tableless HTML Using CSS and jQuery

Wednesday, February 17, 2010

I've seen other vertical text centering techniques and used them successfully in certain situations. There seemed to be other situations where I couldn't get the techniques to work. I figured I'd give jQuery a try and see if I could work it out more easily for a group of objects. For my purposes, creating a list of links, I needed to use a fixed height for the <li>.

Final should look something like this:

So you'll need a list. I was making clickable buttons with backgrounds so my HTML/CSS may have more tags than you'll need. I ended up needing some <span> tags inside the <a> tags, such as:

<div class="vertical1">
<ul>
<li><a href="#"><span>Item 1</span></a></li>
<li><a href="#"><span>Item 2 is a little bit longer</span></a></li>
<li><a href="#"><span>Item 3 is ridiculously long. Hopefully it feels more important now that it has used so much space.</span></a></li>
</ul>
</div>

For CSS, use something like the below. I had needed:
.vertical1 ul,
.vertical1 li    {
    margin: 0;
    padding: 0;
    }
.vertical1 li    {
    background: none;
    height: 135px;
    width: 224px;
    position: relative;
    margin-top: 9px;
    }
.vertical1 a    {
    color: #000;
    height: 135px;
    width: 224px;
    display: block;
    background: none orange;
    border: none;
    }
.vertical1 a:hover    {
    background-position: 0 -135px;
    }
.vertical1 span    {
    position: absolute;
    display: block;
    width: 140px;
    margin-left: 15px;
    line-height: 1.1111em;
    font-size: 12px;
    }

You'll need jQuery. Use something like this:
$(".vertical1 li").each(function () {
       li_height = $(this).height();
       span_height = $(this).find("span").height();
       halfway = (li_height/2) - (span_height/2);
       $(this).find("span").css("top", halfway);
    });

Blog terms:

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p> <h2> <br> <img>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.

John is a rare talent with the ability to cross over between design and programming. Willing to find programming / css solutions to almost any design challenge. I can always count on John to produce clean, efficient and thoughtful websites. John is a great resource, always on top of the latest industry trends. He is the BEST!

M. S., Owner IndigoPark
Copyright ©2001-2017 Way Cool Web Design LLC. All Rights Reserved.