Setting different margin for first child li based on number of list items

I'm trying to set a different CSS margin value for the first LI element in UL based on the number of LI elements. iee

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

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

      

Tried :nth-last-child(n + 3)

it but it doesn't work. Any suggestions? Thanks to

+3


source to share


1 answer


DEMO

styles can be applied to child nodes based on the number of siblings.

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 determine the number of children an element has?

+3


source







All Articles