6

Is it possible to use parent child:nth-child() and only apply to child's?

The html is the following:

<body>
    <div>div 1</div>
    <div>
        div 2
        <div>div 2.1</div>
        <div>div 2.2</div>
    </div>
</body>

And I wanted to select with CSS: div 1 & div 2, I used:

body div:nth-of-type(1) {
    background: red;
    color: white;
}

body div:nth-child(2) {
    background: blue;
}

But div 2.1 & 2.21 got selected too. JSFiddle

Is it possible to do a non recursive selection? If not I guess the only solution are clases or id's..

3 Answers3

6

You can put a > between body and div to select only direct children of body:

body > div:nth-of-type(1) {
    background: red;
    color: white;
}

body > div:nth-child(2) {
    background: blue;
}
<body>
    <div>div 1</div>
    <div>
        div 2
        <div>div 2.1</div>
        <div>div 2.2</div>
    </div>
</body>
Siguza
  • 21,155
  • 6
  • 52
  • 89
1

You can use the ">" character to indicate a parent-child selector. Since 2.1 and 2.2 by default are transparent this doesn't solve the coloring problem so you should style them differently:

https://jsfiddle.net/evccpeeL/1/

div {
    background: white;
}

body > div:nth-of-type(1) {
    background: red;
    color: white;
}

body > div:nth-child(2) {
    background: blue;
}
Sven van de Scheur
  • 1,809
  • 2
  • 15
  • 31
1

You don't actually need to use pseudo-classes here.

You can do this with the direct child selector > alone

body > div {
  background: red;
  color: white;
}
body > div > div {
  background: blue;
  color: white;
  padding-left: 1em;
}
<body>
  <div>div 1</div>
  <div>
    div 2
    <div>div 2.1</div>
    <div>div 2.2</div>
  </div>
</body>

You might find this article useful The 30 CSS Selectors you Must Memorize

Paulie_D
  • 107,962
  • 13
  • 142
  • 161