2015-07-02 97 views
5

我正在寻找只有CSS(无JS)的方式来忽略第n个孩子计数中的隐藏元素。这可能吗?选择第n个孩子跳过隐藏的元素

我有了这个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> 

我努力的目标每秒库项目,是不是空的,但是这不是工作:

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

我不想使用JS,因为这是一个复杂的网站,有很多断点,我不想为这些基本的东西添加onresize监听器。

+1

据我所知,这是不可能的CSS,因为'nth-child(2n)'会指向每个第二个孩子,如果它也有gallery-item类但不是空类,它会得到样式。 – Harry

+0

啊,对于那个错字错误感到抱歉。没有注意到:( – Harry

回答

0

您必须使用下面的代码为目标的第二项

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

链接JSFIDDLE

+2

问题状态*指定每个第二个图库项目不是空的*而不仅仅是第二个项目。 – Harry

1

这可能是一个零后,因为它使用JS。但在这种情况下,它似乎只是一个选择。你不想使用JS,我知道。但就没有一个带有CSS唯一的解决办法,至少可以这样考虑: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) 
}); 

,然后只需添加.notEmptyAndEven选择你需要的CSS规则。