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>
<li>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?
You create an unordered list using the ul tag. Then, you use the li tag to list each and every one of the items you want your list to include.
Unordered list or Bulleted list (ul) Ordered list or Numbered list (ol) Description list or Definition list (dl)
Add a margin to your li tags. That will create space between the li and you can use line-height to set the spacing to the text within the li tags. Save this answer.
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With