How can I use :nth-child() to select every other <div> within ALL children?

两盒软妹~` 提交于 2019-12-11 00:14:49

问题


I'm working on a comments system, and I need to have every other child <div> (even children of the first children) be selected with CSS.

For example, lets say I have this markup (omitting unneeded closing tags just for simplicity):

 <body>
<div class="comment">
    <div class="comment"/>
    <p class="something else"/>
    <div class="comment">
        <div class="comment"/>
        <div class="comment"/>
    </div>
</div>
<div class="comment"/>
<div class="comment"/>
</body>

How can I select every other <div> within the body (excluding <p>)?

What I basically want is for it to turn out like this:

(Two stars is even, one star is odd, regular is neither)

 <body>
    **<div class="comment">**
        *<div class="comment"/>*
        <p class="something else"/>
        **<div class="comment">**
            *<div class="comment"/>*
            **<div class="comment"/>**
        </div>
    </div>
    *<div class="comment"/>*
    **<div class="comment"/>**
    </body>

I need it to walk through every other <div> in order, applying the styles.

Is there anyway to do this?


回答1:


- Advanced demo with multiThread colored comments
- Simple demo

Ugh this took a while just to understand from OP that "even" / "odd" are actually not the CSS's even and odd but the index of appearance of a .comment div, (nested or not).

CSS? Almost impossible if not even impossible. (possible only with nesting too much styles to cover all possibilities)

With jQuery simply like:

$('.comment').addClass(function(i){
  return i%2 ? "odd" : "even";
});

where i represents the Element's Array Index position (0,1,2,3...) of that .comment element jquery collected on it's way. Now if i reminder 2 returns 0 add the "even" class, else : add the "odd" class to that element.

CSS:

div.comment{
  /* Common styles */
  color:#fff;
  margin:5px;
  border:1px solid #000;
}
.even { background:blue; } /* jQ Index: 0, 2, 4, 6, 8... */
.odd  { background:red;  } /* jQ Index: ...1, 3, 5, 7... */


来源:https://stackoverflow.com/questions/25715302/how-can-i-use-nth-child-to-select-every-other-div-within-all-children

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