3

The child selector should select the immediate children contained by an element. But in the following code, the selector div > ul > li select all descendant <li> of <div>. I have no idea why the child selector expands its scope?

div>ul>li {
  text-decoration: underline;
  color: blue;
}
<div>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3
      <ul>
        <li>Item 31</li>
        <li>Item 32</li>
      </ul>
    </li>
  </ul>
</div>
misterManSam
  • 24,303
  • 11
  • 69
  • 89
Parmenides
  • 85
  • 6

2 Answers2

5

If you take a look at the page in Chrome or Firefox's developer tools, you'll see what's happening. The selector isn't applying to the further descendants—instead, they're inheriting the color from their parent.

By default, the color property isn't set. This is equivalent to setting color: inherit;—in other words, it means "since I have no special instructions, I'll do whatever my parent is doing". So when you set a color for an element, it'll also apply to all that element's descendants, unless any of them specify a color of their own.

Draconis
  • 3,209
  • 1
  • 19
  • 31
  • And even though [`text-decoration`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) isn't an inherited property, it also applies to descendants. _"Text decorations are drawn across descendant text elements. This means that if an element specifies a text decoration, then a child element can't remove the decoration."_ – j08691 Apr 08 '19 at 03:29
  • @j08691 Very good point! I can edit that into my answer, or you can post it as an answer of your own if you'd like the rep for it. – Draconis Apr 08 '19 at 03:30
1

@Draconis' answer is off to a good start, but the comments suggest there is no solution to the underlining. So here is a solution.

/* Set all list elements to a default value. change this to what you need it to be */
li {
  color: black;
  text-decoration: none;
}
/* Then set the inner ULs to full width inline-block; which will prevent the
   text-decoration from inheriting into them */
div>ul ul {
  display:inline-block;
  width: calc(100% - 40px);
}

div>ul>li {
  text-decoration: underline;
  color: blue;
}
<div>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3
      <ul>
        <li>Item 31</li>
        <li>Item 32</li>
      </ul>
    </li>
  </ul>
</div>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150