I'm using the following css to alternate the background colour of li elements, but need the css to be maintained if the rows get the .hidden class assigned to them (.hidden class being display: none;).
ul li:not(.hidden):nth-child(odd) {
background: #fff;
}
ul li:not(.hidden):nth-child(even) {
background: #f4f4f4;
}
Any ideas on how to keep the alternating colours w开发者_JAVA技巧hile adding / removing li elements to / from the ul? Please only give a CSS based solution if possible. I may have to do it in JS but would prefer not to!
Cheers
Due to the way the :not()
pseudo-class works, you cannot use it to filter elements out of the DOM to obtain a subset of elements on which to apply styles. See this answer for the nitty gritty.
EDIT: Apparently my solution below isn't supposed to work either. I need to take a break from answering questions or something. So I guess the only other feasible route may be to do this with JavaScript. I'm keeping this post here instead of deleting as I don't want to take the comments down with it.
To this end, if you can modify the HTML, you can instead use a class that is common to all your li
s and target that instead, in conjunction with :nth-of-type()
:
ul li.shown:nth-of-type(odd) {
background: #fff;
}
ul li.shown:nth-of-type(even) {
background: #f4f4f4;
}
What if you changed your .hidden to the following
.hidden {height:0px; overflow:hidden}
I haven't tested this code at all, but the elements would still be in the DOM for manipulation yet shouldn't be visible to the user.
精彩评论