• 1
  • 2
  • 3
  • 4
  • 5...">

    CSS pseudo-class ordering: nth-child and: not

    I have the following code:

    <ul class="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

    I wrote this list with gray stripes:

     .list li:nth-child(2n) { background-color: #ccc; } 

    Works great, but then I hide some li elements and the order of the strip breaks. Fiddle

    I tried updating the selector with :not() :

     .list li:not(.hidden):nth-child(2n) { background-color: #ccc; } 

    But it was useless.

    Can anyone advise how to arrange the pseudo-classes in order to keep the strip order?

    +6
    source share
    1 answer

    AFAIK, nth-child works with item positions or index. Thus, even if you hide an element, other positions / indices of the elements do not change.

    I think your best option here is to do this completely with jQuery, as shown below, as an example:

     $(function () { $('.list li:not(.hidden):odd').addClass('paint'); $('.hide_some').click(function () { $('.list li').eq(0).addClass('hidden'); $('.list li').eq(2).addClass('hidden'); $('.list li').eq(5).addClass('hidden'); // again remove the paint $('.list li').removeClass('paint'); // again add new paint $('.list li:not(".hidden"):odd').addClass('paint'); }) }) 

    Working script

    +1
    source

    Source: https://habr.com/ru/post/970677/


    All Articles