Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS pseudo classes ordering :nth-child and :not [duplicate]

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've styled this list with grey stripes:

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

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

I've tried updating the selector with :not():

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

But this was useless.

Could anyone advice how to order pseudo classes to keep stripes order?

like image 947
Evgeniy Avatar asked Jun 11 '14 07:06

Evgeniy


People also ask

How do I select a specific Nth child in CSS?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

Is nth child a pseudo element?

The :nth-child() pseudo-class represents an element that has an+b siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

What's the difference between the nth of type () and Nth child () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .

Which of the following is the recommended order of pseudo-classes?

The recommended order is link,visited,focus,hover,active. The :link and :visited pseudo-classes should generally come first.


1 Answers

AFAIK, nth-child works on element positions or index. So, even if you hide the element, the other element positions/indexes doesn't change.

I think your better option here is to do this completely with jQuery as I shown below as just 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 Fiddle

like image 80
Mr_Green Avatar answered Sep 30 '22 13:09

Mr_Green