Search code examples
htmlcsscss-selectors

by using :nth-of-type I'm trying to select the fist div inside the div #benefits-section, but for some reason it selects all div tags


Following are the HTML and CSS that I'm working on.

    https://jsfiddle.net/mpgsrwt0/
 #benefits-section h2{
display: block;
font-size: 2rem;
font-family: Outfit;
font-weight: 500;
margin-bottom: 1rem;
}

#benefits-section div:nth-of-type(1){
background-color: yellow;
}

When I try using the nth of type on the second and third div, it works.

OR when I try using the selector for the first div, it stops working. it selects all the div tags and applies background on it. I'm not sure what is causing this error.


Solution

  • All the inner divs you have are the first children of that type so they are correctly all colored yellow.

    You want to target only the div that is the direct child (not a grandchild), so change this:

    
         #benefits-section div:nth-of-type(1) {
           background-color: yellow;
         }
    

    to this:

         #benefits-section > div:nth-of-type(1) {
           background-color: yellow;
         }