开发者

Set width of list items to fill unordered list

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>
    <开发者_如何学Cli>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?


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.


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.


This is also possible just with css, but will only work in modern browsers.

ul {
    /* ... */
    display: table;
}

li {
    /* ... */
    display: table-cell;
}


Using jQuery, you can do something like this :

var li = $('#mylist li').size();
var liWidth = 100 / li;

$('#mylist li').width(liWidth + '%');

assuming your HTML looks like:

<ul id="mylist">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>


Here's a working fiddle : http://jsfiddle.net/vDVvm/7/


Here is an improvement on vzwick's function:

(function( $ ){
  $.fn.autowidth = function() {
    return this.each(function() {
        var w = $(this).width();
        var liw = w / $(this).children('li').length;
        $(this).children('li').each(function(){
            var s = $(this).outerWidth(true)-$(this).width();
            $(this).width(liw-s);
        });
    });
  };
})( jQuery );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜