htmlcsssasslesspseudo-element

How not to access second last two elements by CSS


How can I add "," separated content: "," to all ul > li not the last two lists

<style>
 ul li:nth-last-child(2)::after { content: "," } 
</style>

is not working

I've tried to separete all the li items with commas separeated except the last two item because the last one is hidden and the 2nd last one I don't want to show commas after it as it is the last item of shown li items.


Solution

  • You can use the :nth-last-child to start counting from the bottom, along with :not():

    ul li:not(:nth-last-child(-n + 2))::after {
       content: "," 
    }
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
      <li>Five</li>
    </ul>
    
    <p>A couple more tests...</p>
    
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
    </ul>
    
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
    
    
    <p>Edge cases (elements &lt; 4): These ones are tricky and it's up to you to tweak according to your requirements</p>
    
    <ul>
      <li>One</li>
      <li>Two</li>
    </ul>
    
    <ul>
      <li>One</li>
    </ul>