So today I was asked to come up with an easy way to make some li elements fill an unordered list. Sounds easy, right?
The trick was that the li elements were to be all different sizes, and therefore needed to be scaled individually. My solution was to find the width of the parent element, then loop through all the child elements and scale them by 1 pixel each time until they reach the size of the parent container.
Sure it’s probably not the best solution, but it definitely worked.
The HTML:
The CSS:
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
.list-wrap {
width:960px;
margin: 0 auto;
}
ul.example {
width:600px;
height: 28px;
margin: 0 auto;
padding: 5px;
overflow: hidden;
position: relative;
border: 1px #000000 solid;
}
ul.example li {
display: inline-block;
position: relative;
list-style: none;
padding:0;
margin:0;
height: 28px;
line-height:28px;
text-align: center;
background: #E8E8E8;
}
The jQuery:
var sumwidth=0;
var increaseWidth = 1;
var i = 0;
var theParent = $("ul.example");
theParent.children().each(function() {
i++;
});
var maxWidth = theParent.width() - (i*i);
while( sumwidth < maxWidth) {
sumwidth = 0;
theParent.children().each(function() {
var getWidth = $(this).width();
var newWidth = getWidth + increaseWidth;
$(this).css('width', newWidth + 'px');
sumwidth +=$(this).width();
});
}
Also, the ratio between the width of the container and the font size will be dependant if the function breaks!
You can also check out the example here.
Have fun!





