Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting nth-child skipping hidden elements [duplicate]

I'm looking for a CSS only (no JS) way to ignore hidden elements in nth-child counts. Is this possible?

I've got 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'm trying to target every second gallery-item that is not empty, but this isn't working:

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

I don't want to use JS because this is a complex site that has many breakpoints and I don't want to add onresize listeners for something this basic.

like image 971
user909410 Avatar asked Nov 21 '22 12:11

user909410


1 Answers

This may be a zero-post, because it uses JS. However it seems to be only option in this case. You didn't want to use JS, which I understand. But as far no-one comes with 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 .notEmptyAndEven selector and the CSS rules you need.

like image 120
Samuli Hakoniemi Avatar answered Dec 04 '22 08:12

Samuli Hakoniemi