How Do I Vertically Align Divs within a List?

August 23, 2012

Aligning things in the middle and centered is something quite common, but it can be a challenge to figure out on your own.

Let’s say you’re making a quiz which populates the answers and the select buttons from a database. Let’s say the answers vary from 1 to 3 lines. The easiest thing to do is to put the answers and their corresponding buttons in a table and then align the table cells to the middle.

But you should never (Well, almost never…) put things into tables. And in this case, you’re lucky not to need to put them in a table.

First, create an unordered list with list items for each answer. (ul and li)

You have two choices at this point. You can either make another ul and li within your li and make the structure look like above, or you can (better) put divs inside of your li’s:

 <ul>
    <li>
<ul>
    <li>Answer button 1</li>
    <li>Answer 1</li>
</ul>
</li>
<li>
<ul>
    <li>Answer button 2</li>
    <li>Answer 2</li>
</ul>
<li>
</ul>

Once you have your list laid out, I’ll encourage you to replace the inner ul and li with div’s instead. Nested lists are too ugly and there’s too much to keep track of when formatting it.

 <ul>
    <li>
    <div id="answer-btn-1">Answer button 1</div>
    <div id="answer-1">Answer 1</div>
    </li>
    <li>
    <div id="answer-btn-2">Answer button 2</div>
    <div id="answer-2">Answer 2</div>
    </li>
</ul>

Now that you’re all set with your div’s inside of lists, you’ll need to style the divs within the lists to allow them to center vertically in the middle. Here’s the CSS:

li div {
display:table-cell;
vertical-align:middle;
width:700px;
}

The first style formats the divs as though they were table cells. The second line makes them align middle (which is now possible, since they’re being styled as table cells). The final one is just setting the width of your new “cells”

Now you’ll want to make sure that your answer divs are aligned in the middle vertically (vertical-align: middle;) But not horizontally (unless you want them horizontally aligned.) Then you want to eliminate floats, since the float will cause the divs to display all right next to each other. If these three lines don’t do it, you could try working with a height property and fixing the height. But if it’s working fine without a height property, why make your work more difficult than it needs to be?

With these fixes, you should be able to align just about anything in the center.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive