Reputation: 57
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
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-nav
s with lists in them... like this:
$('.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
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