Parmenides
Parmenides

Reputation: 85

Why does the child selector select all descendants?

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>

Upvotes: 3

Views: 97

Answers (2)

Mr Lister
Mr Lister

Reputation: 46589

@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>

Upvotes: 1

Draconis
Draconis

Reputation: 3491

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.

Upvotes: 5

Related Questions