Search code examples
htmlcssstylesparadigms

Why use ">" in CSS?


If I want to add styling to all p elements inside of a div, why should I use

div > p{

  *style here*

}

as opposed to just

div p{

  *style here*

}

furthermore, if I want to use a pseudo class, why would I then choose to use ">"

div > p:first-child{

  *style here*

}

instead of

 div p:first-child{

   *style here*

 }

Are there any benefits or drawbacks? what does that operator do?


Solution

  • It's the direct child, not a recursive match.

    CSS

    div > p {
    
    }
    

    HTML

    <div>
       <p>Match</p>
       <span>
          <p>No match</p>
       </span>
    </div>
    

    CSS

    div p {
    
    }
    

    Markup

    <div>
       <p>Match</p>
       <span>
          <p>Match</p>
       </span>
    </div>