CSS nth-of-type selector with nested elements

后端 未结 2 1512
刺人心
刺人心 2020-12-19 04:33

I have a number of divs of a particular class .box for which I want to set an alternating background color. However, some of the divs are placed inside another div .inner-co

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 04:53

    You can still apply an alternating background with CSS only here. Here's a Fiddle of it in action.

    There's 2 ways you can do it:

    Method 1:

    Target the each level of

    s directly.

    .container > .box:nth-child(even) {
        /* stuff */
    }
    

    The method above targets only the first level children of the parent .container. This won't effect the

    s inside .inner-container.

    To target the

    s inside .inner-container separately, we use the same trick again, but start with a different parent container:

    .inner-container > .box:nth-child(even) {
        /* stuff */
    }
    

    Method 2:

    Add a second class for the nested

    s and target them that way:

    a div
    a div
    a div
    a nested div

提交回复
热议问题