skip to Main Content

Which is the correct selector to select all li items inside .nav class ?

Have tried both and they seem to both work. Want to know what the correct way of writing the selector

Trying to style all list items inside .nav class. I know its a basic question but all sites say something different

2

Answers


  1. It depends on what you mean by selecting all childs:

    • .nav li: This is called Decendand combinator, which selects all li that has an ancestor with class .nav, no matter if there are intermediate layers between.
    • .nav > li: This is called Child combinator, which only selects the immediate child elements under.nav. (For example, .nav > ol > li won’t be selected)
    .nav li {
      color: red;
    }
    
    .nav>li {
      color: blue;
    }
    <div class="nav">
    
      <li>Direct Child</li>
      
      <ol>
        <li>Not Direct Child</li>
      </ol>
      
    </div>
    Login or Signup to reply.
  2. I think .nav li would be best. If you’re using <ul> elements around your <li> elements then the .nav > li won’t select them, because it only looks for li elements that are first-layer children of .nav elements instead of all <li> elements under something with class .nav Might be of help to read these pages on css selectors to explain:

    w3schools css selector guide

    mdn web docs "descendant combinator" css selector explanation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search