4

I'm trying to set a different CSS margin value to the first element of LI in UL depending on the number of LI elements. i.e

<ul>
 <li> (margin: 20%)
 <li>
 <li>
</ul>

<ul>
 <li> (margin: 40%)
 <li>
</ul>

Tried with :nth-last-child(n + 3) but it doesn't work. Any suggestions? Thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Rani Einav
  • 43
  • 4
  • Somehow I had forgotten about that duplicate question, despite having had quite a bit of involvement in it in the past. – BoltClock May 29 '15 at 14:57

1 Answers1

3

DEMO

styles can be applied to the children nodes based on the number of siblings they have.

html

<ul>
    <li>one item</li>
</ul>

<ul>
    <li>two items</li>
    <li>two items</li>
</ul>

<ul>
    <li>three items</li>
    <li>three items</li>
    <li>three items</li>
</ul>

<ul>
    <li>four items</li>
    <li>four items</li>
    <li>four items</li>
    <li>four items</li>
</ul>

css

 li:first-child:nth-last-child(1) {
    margin-left: 0px;
}

li:first-child:nth-last-child(2) ~ li {
    margin-left: 0px;
}

li:first-child:nth-last-child(3) ~ li {
    margin-left: 0px;
}

li:first-child:nth-last-child(4) ~ li {
    margin-left: 0px;
}

 li:first-child:nth-last-child(4) {
     margin-left:10px;
    color:red;
 }

 li:first-child:nth-last-child(3) {
     margin-left:20px;
    color:green;
 }

 li:first-child:nth-last-child(2) {
     margin-left:30px;
    color:blue;
 }

 li:first-child:nth-last-child(1) {
     margin-left:40px;
     color:gray;
 }

ref : Can CSS detect the number of children an element has?

Community
  • 1
  • 1
4dgaurav
  • 11,360
  • 4
  • 32
  • 59