Awais Imran
Awais Imran

Reputation: 1344

Change <ul> width as per number of <li>

Can we change the <ul> width as per number of <li>?

Example:

  1. <li> = 100px of <ul> width
  2. <li> = 200px of <ul> width
  3. <li> = 300px of <ul> width
  4. <li> = 400px of <ul> width
  5. <li> = 500px of <ul> width
  6. <li> = 600px of <ul> width

and so on....

Upvotes: 0

Views: 1518

Answers (6)

midstack
midstack

Reputation: 2123

Try this;

HTML

<ul id="pr">
    <li>
        <ul>
            <li>List-1</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>List-2</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>List-3</li>
        </ul>
    </li>
</ul>

JS

var pr = $('#pr').children('li');
$.each(pr,function(k,v){
     $(this).children('ul').width(k*100+100);  
})

jsfiddle

http://jsfiddle.net/2N9Es/2/

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Why are you not using just width: auto;?

ul{
 width: auto;
}
li{
 display: inline-block;
}

will work for you!


Or, if you wanted to do it with jQuery, you can do as others suggested like this:

var liwidth = $(ul li).length * 100;
$('ul').css('width',liwidth);

Upvotes: 1

Steve Robbins
Steve Robbins

Reputation: 13812

Don't you dare use JS.

What's wrong with

li {
    float: left;
    width: 100px;
}

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

CSS is all you neeed

DEMO

Just give dispaly:inline-block in CSS to your UL

Upvotes: 1

Felix
Felix

Reputation: 38102

You can use:

$('ul').each(function() {
    $(this).width($(this).find('li').length*100);
});

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

var cache = $('ul')
cache.width(cache.children('li').length * 100);

Upvotes: 0

Related Questions