Choosing nth-child to skip hidden elements

I am only looking for a CSS method (without JS) to ignore hidden elements in nth-child counts. Is it possible?

I have this HTML:

<div class="gallery-item"><img src="http://placehold.it/150x150"></div> <div class="gallery-item"><img src="http://placehold.it/150x150"></div> <div class="gallery-item empty"></div> <div class="gallery-item"><img src="http://placehold.it/150x150"></div> <div class="gallery-item empty"></div> <div class="gallery-item"><img src="http://placehold.it/150x150"></div> <div class="gallery-item"><img src="http://placehold.it/150x150"></div> 

I am trying to target every second element of the gallery, which is not empty, but this does not work:

.gallery-item:not(.empty):nth-child(2n) {}

I do not want to use JS because it is a complex site with many breakpoints, and I do not want to add onresize listeners for something so basic.

+5
source share
2 answers

It could be a zero post because it uses JS. However, it seems that this is an option only in this case. You did not want to use JS, which I understand. But so far no one has come up with a CSS-only solution, at least consider this: http://codepen.io/zvona/pen/jPZYNx

 var galleryItems = document.querySelectorAll('.gallery-item:not(.empty)'); [].forEach.call(galleryItems, function(item, i) { item.classList.toggle('notEmptyAndEven', i % 2) }); 

and then just add the .notEmptyAndEven selector and the necessary CSS rules.

+1
source

You should use the code below to target the second element

 .gallery-item:not(.empty):nth-child(2) { //not :nth-child(2n) background:#ddd } 

JSFIDDLE Link

-1
source

All Articles