7

I'm trying to figure out a way to vertically center an unordered list within a div. I found a number of ways to do this, however the li tags within my ul tag have PHP code in them that gets text from a database and this causes the length of the text within the li tags to vary in length significantly causing vertical sifting within my div which has a fixed height and width.

How can I vertically position my unordered list so it'll always be vertically aligned within this div?

Wex
  • 15,539
  • 10
  • 64
  • 107
Charlie
  • 219
  • 1
  • 4
  • 6

2 Answers2

7

If you're trying to center horizontally, here is a bit of code that will work for any length:

Preview: http://jsfiddle.net/Wexcode/6UtFz/

HTML:

<div>
    <ul>
        <li><a href="#">Element 1</a></li>
        <li><a href="#">Element 2</a></li>
        <li><a href="#">Element 3</a></li>
        <li><a href="#">Element 4</a></li>
    </ul>
</div>

CSS:

div { overflow: hidden; }
ul { 
    position: relative;
    float: left;
    left: 50%;
    padding: 0;
    list-style: none; }
li { 
    position: relative;
    float: left;
    right: 50%;
    margin: 0 5px; }

For vertical-centering, just make use of the vertical-align property.
See: http://jsfiddle.net/Wexcode/fK793/

Wex
  • 15,539
  • 10
  • 64
  • 107
  • 1
    Great Answer Wex! I wish I could accept your answer, since it looks like Charlie is never coming back. – Arel Nov 14 '12 at 17:54
1

It's pretty simple. Just use display:table; for the parent div and display:table-cell; and vertical-align:middle; for the child.

Fiddle: https://jsfiddle.net/fzfa312m/

div { 
    background: #f2f2f2;
    width: 300px; 
    height: 300px; 
    display:table; }

ul {
    vertical-align: middle; 
    display: table-cell; }
<div>
    <ul>
        <li><a href="#">Element 1</a></li>
        <li><a href="#">Element 2</a></li>
        <li><a href="#">Element 3</a></li>
        <li><a href="#">Element 4</a></li>
    </ul>
</div>
gopalraju
  • 2,299
  • 1
  • 12
  • 15