user3758403
user3758403

Reputation: 57

dynamic width of li based on number of lis in a set

I want to set dynamic width to li(s) based on how many li(s) are there in list. For example if there are 18 li(s). Each width should be 100% / 18 = 5.55%. Also what should I do if I would have 3 different sets of ul. I tried to use this.

$('.lesson-nav ul li').width( 100 / $(".lesson-nav ul li").length + '%' );

For unknown reason: This script gives width 120% while there is only 1 li and 27.55% when there are 18 lis.

Upvotes: 3

Views: 464

Answers (2)

Smern
Smern

Reputation: 19086

While I cannot reproduce your 120% problem. To answer your question about "what should I do if I would have 3 different sets of ul", assuming you have 3 different .lesson-navs with lists in them... like this:

JSFiddle

$('.lesson-nav').each( function() {
    $lis = $(this).find('ul li');
    $lis.width( 100 / $lis.length + '%' );
});

If you have multiple sets of ul within a single .lesson-nav then you can modify your selectors a little bit like seen in this JSFiddle

You could also replace the width() with css("width",...) here if width() isn't working for whatever reason.

Upvotes: 1

nicael
nicael

Reputation: 19049

As per documentation:

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px).

So you should use css(width)

$('.lesson-nav ul li').css("width", 100 / $(".lesson-nav ul li").length + '%' );

Upvotes: 1

Related Questions