Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set width of list items to fill unordered list

Tags:

html

jquery

css

So I have a horizontal unordered list with a set width. Inside, I have a dynamic number of list items. It could be 2 items, or 6 - it depends on several factors.

I'd like to be able to set the width of each list item so that they fill the entire width of the ul, no matter how many items are inside. So if there was 1 list item, it's width would be 100%; 2, and they would both be 50%, and so on.

Here's my HTML and CSS:

ul
{
    width: 300px;
    height: 50px;
    background-color: #000000;
    list-style: none;
    margin: 0;
    padding: 0;
}

li
{
    float: left;
    height: 50px;
    background-color: #4265CE;
    margin: 0;
    padding: 0;
}

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

Here it is in jFiddle: http://jsfiddle.net/vDVvm/3/

Is there a way to do this with CSS, or will I have to use jQuery?

like image 343
Steven Avatar asked Sep 23 '11 19:09

Steven


People also ask

How do you make an unordered list a list with the items in bullets?

You create an unordered list using the ul tag. Then, you use the li tag to list each and every one of the items you want your list to include.

What are the 3 types of unordered list?

Unordered list or Bulleted list (ul) Ordered list or Numbered list (ol) Description list or Definition list (dl)

How do I add a space between an ordered list in HTML?

Add a margin to your li tags. That will create space between the li and you can use line-height to set the spacing to the text within the li tags. Save this answer.

What can be the list item marker for an unordered list?

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.


2 Answers

No way with pure CSS, I'm afraid.

Edit: Most proper jQuery solution i can think of: http://jsfiddle.net/vDVvm/8/

(function( $ ){
  $.fn.autowidth = function() {
    return this.each(function() {        
        $('li', this).css({'width' : (100 / $('li', this).length) + '%'})
    });
  };
})( jQuery );

$(document).ready(function(){
    $('.fill-me').autowidth();    
});

Keep in mind though, that whenever (100 % number_of_lis !== 0), you're gonna be running into some nasty problems with rounding errors.

like image 130
vzwick Avatar answered Nov 15 '22 00:11

vzwick


A solution without JavaScript.

ul
{
    width: 300px;
    height: 50px;
    background-color: #000000;
    list-style: none;
    margin: 0;
    padding: 0;
    display: table;
}

li
{
    height: 50px;
    background-color: #4265CE;
    margin: 0;
    padding: 0;
    display: table-cell;
}

http://jsfiddle.net/vDVvm/5/

It may be not cross browser enough, however.

like image 36
Michas Avatar answered Nov 15 '22 01:11

Michas