0

I have an unordered list with a fixed width of 100px with nested li. Each li is filled with a background color.

The number of nested li could range from 1 to 5. I want to display a color pallette where each li would represent a color. However, the width of the li should be equal depending on how many nested li are in the ul. For instance if there is only one li with id = "1", then

#1{
    width: 100%;
    height:20px;
    color: #222222;
}

if there are two the its width should be 50% of the ul and so on.

I'm able to do this using using php and inline css but I'm curious if there is a way to do this with pure css in a stylesheet. Any help is deeply appreciated.

Sample markup with 1 <li>

<ul>
  <li id="1"></li>
</ul>
Passerby
  • 9,715
  • 2
  • 33
  • 50
Kwaasi Djin
  • 125
  • 1
  • 11
  • How do you do it in php? – witherwind Apr 01 '14 at 02:57
  • In php I would know before hand how many nested li exist and echo an inline style with the corresponding widths. So if there are 5 li then each li would have a width of 20%, if there are 4 then 25%;3 33.3% and so on – Kwaasi Djin Apr 01 '14 at 03:12

2 Answers2

1

I think what you're asking is basically

I have up to 5 sibling elements which must fill their parent and maintain equal width

… in which case, you want display:flexbox. I'll give you an example (maintaining the unordered-list syntax from your question, although this isn't necessary)

ul {
  display:flex; /* lay out children using "flexible box" rules */
}
li {
  flex-grow:1; /* all children will expand equally to fill their parent */
  list-style-type:none; /* don't show the normal "bullet" next to each entry */
}

flexbox is new-ish, so there are some compatibility concerns if you deal with old browsers.

For further information, css-tricks.com has a number of good guides for flexbox.

Jeremy
  • 2,642
  • 18
  • 36
0

A similar question was asked here: Can CSS detect the number of children an element has? and the solution is possible using pure css3 - so it is possible, but you will need to accommodate for older browsers.

/* one item */
li: first-child:nth-last-child(1) {
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

/* five items */
li:first-child:nth-last-child(5),
li:first-child:nth-last-child(5) ~ li {
    width: 20%;
}

It seems that it should solve your problem.

Community
  • 1
  • 1
JRulle
  • 7,448
  • 6
  • 39
  • 61