nth-child selecting wrong element

寵の児 提交于 2019-12-19 10:57:52

问题


For this particular site, when I utilize nth-child via CSS or jQuery, the 'nth-child' selector is capturing the wrong element. I'm getting one child before the selector that I'm calling:

.home article:nth-child(3) {} //captures 2nd child

This seems to be capturing the second child instead. If I attempt:

.home article:nth-child(1) {} //captures nothing

This captures no elements. In jQuery, it shows up as an empty array. Here's the dev site that I'm working on. Thank you.

http://heilbrice.designliftoff.com/


回答1:


In your site, you have a clearfix div that's the first child of its parent element within your container, so your first article is really the second child, not the first:

<div class="row-main clearfix">
    <div class="clearfix"></div>  <!-- .row-main.clearfix > :nth-child(1) -->

    <article id="post-" class=""> <!-- .row-main.clearfix > :nth-child(2) -->

In CSS, you can use :nth-of-type() instead to reach the third article element:

/* Select the 3rd article in its parent within .home */
.home article:nth-of-type(3) {}

Oddly enough, jQuery does not support :nth-of-type(), so for a cross-browser solution you have to opt with :eq() with a zero-based index:

// Select the 3rd article within .home
$('.home article:eq(2)')


来源:https://stackoverflow.com/questions/11633646/nth-child-selecting-wrong-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!