Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center an unordered list with dynamic content within div?

Tags:

html

css

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?

like image 538
Charlie Avatar asked Jan 04 '12 21:01

Charlie


People also ask

How do you center align an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element. Now, add the style to the div class and use the text-align property with center as its value.

How do you center align in UL?

Just give the list centered text (e.g. ul. nav { text-align: center; } ) and the list items inline-block (e.g. ul. nav li { display: inline-block; } ). If you want to do it with margin for whatever reason, look into width: fit-content; .

How do I align content in the middle of a div?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.


2 Answers

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/

like image 83
Wex Avatar answered Oct 13 '22 15:10

Wex


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>
like image 35
gopalraju Avatar answered Oct 13 '22 14:10

gopalraju