0

I want to select only parent elements but it's not work corrrectly(or I don't do properly.) How to select only parent elements?

body > ul > li {
  color: green;
}
<body>
  <ul>
    <li>parent</li>
    <li>parent
      <ul>
        <li>child</li>
        <li>child</li>
      </ul>
    </li>
    <li>parent</li>
    <li>parent</li>
  </ul>
</body>
black
  • 703
  • 2
  • 7
  • 16

4 Answers4

3

You are facing the inheritance behavior. You are setting the color to only the parent but child are inheriting this color too.

enter image description here

You need to reset the style for child:

body > ul > li {
  color: green;
}
body > ul > li > ul {
  color:initial;
}
<body>
  <ul>
    <li>parent</li>
    <li>parent
      <ul>
        <li>child</li>
        <li>child</li>
      </ul>
    </li>
    <li>parent</li>
    <li>parent</li>
  </ul>
</body>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
1

Your inner <ul> takes css from parent. You need to overwrite this

body > ul > li {
  color: green;
}

body > ul > li ul {
    color: black;
}
<body>
  <ul>
    <li>parent</li>
    <li>parent
      <ul>
        <li>child</li>
        <li>child</li>
      </ul>
    </li>
    <li>parent</li>
    <li>parent</li>
  </ul>
</body>
Justinas
  • 41,402
  • 5
  • 66
  • 96
1

body > ul > li {
  color: green;
}

body > ul > li > ul {
    color: initial;
}
<body>
  <ul>
    <li>parent</li>
    <li>parent
      <ul>
        <li>child</li>
        <li>child</li>
      </ul>
    </li>
    <li>parent</li>
    <li>parent</li>
  </ul>
</body>
satyajit rout
  • 1,623
  • 10
  • 20
-2

Try

body  ul  li { color: green; }
Chuka Okoye
  • 132
  • 3