CSS global :nth-of-type selector (:nth-of-class)

2019-02-20 10:58发布

问题:

What CSS selector can be used to select all odd elements inside a parent, but which are not necessarily siblings?

<div id="parent">
    <div>
        <div class="element">A</div>            
    </div>
    <div class="element">A</div>   
    <div class="element">A</div>         
    <div>
        <div class="element">A</div>            
    </div>
    <div class="element">A</div>            
<div>

What I want is to select every element in parent and apply a style only for odd-indexed ones in this list.

Demo on jsFiddle.

回答1:

While it uses JavaScript, you could style the odd element without altering your markup:

$('.parent .element:odd').css('font-weight', 'bold');

​ http://jsfiddle.net/ansonhoyt/MfxYF/



回答2:

I couldn't get it down to single selector, but with two...

.parent > .element:nth-of-type(2n){
  background:#afa !important;
}
.parent > div:nth-of-type(2n) > .element {
  background:#afa !important;
}

View it on JSFiddle