5

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.

cimmanon
  • 67,211
  • 17
  • 165
  • 171
mynameisnotallowed
  • 564
  • 1
  • 11
  • 34
  • 1
    As far as I know this is not possible with CSS because `nth-child(2n)` would point to every 2nd child and it would get the style if it also has gallery-item class but not empty class. – Harry Jul 02 '15 at 10:02
  • Ah, sorry for that typo error. Did not notice :( – Harry Jul 02 '15 at 10:11

2 Answers2

1

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.

Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
-2

You must use below code to target the second item

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

Link JSFIDDLE

Adarsh Gowda K R
  • 941
  • 8
  • 15
  • 3
    Question states *target every second gallery-item that is not empty* and not just the second item. – Harry Jul 02 '15 at 10:32