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">
<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>

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

This question is for testing whether you are a human visitor and to prevent automated spam submissions.
John is a great web designer and developer and a pleasure to work with. I wish I had more projects that required John's expertise. He's fast and flexible... what more could you ask for in the web services department? Despite many rounds of edits, far exceeding the scope of work, John remained poised and customer focused, willing to do whatever was needed to deliver the desired final product.
T. J., Senior Manager ENC Marketing & Communications, Inc.
Copyright ©2001-2017 Way Cool Web Design LLC. All Rights Reserved.