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?
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.
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.
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 .
The recommended order is link,visited,focus,hover,active. The :link and :visited pseudo-classes should generally come first.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With