jchwebdev
jchwebdev

Reputation: 5450

Why do Child CSS Elements inherit from > Selector unless an explicit behavior is specified?

Given the following:

.site-map > li {
  color: #f00;
}
<ul class="site-map">
  <li>
    <ul>
      <li>I expect this to be black (default color) 1</li>
      <li>I expect this to be black (default color)</li>
    </ul>
  <li>First Level Red</li>
</ul>

...What seems to happen is that the child li are still red UNLESS I make the following adjustment:

.site-map li { color: #000; }
.site-map > li { color: #f00; }
<ul class="site-map">
  <li>
    <ul>
      <li>I expect this to be black (default color) 1</li>
      <li>I expect this to be black (default color)</li>
    </ul>
  <li>First Level Red</li>
</ul>

So it appears that unless one -explicitly- specifies a default for the children, then those children -still- inherit the style from .sitemap > li.

Do I have this correct? I'm confused as to why this should be the case.

Can someone please explain the logic behind this?

Upvotes: 1

Views: 72

Answers (2)

DaniP
DaniP

Reputation: 38252

Based on the W3 Documentation, the color property has this:

Value: <.color.> | inherit
Initial: depends on user agent
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value: as specified

Then we can know by the first two lines, if the element hasn't an initial value defined by the user agent ("browser default stylesheet") will inherit the color from the parent element.


An example with initial value defined by the user agent will be the a tag, this has from the user agent:

a:-webkit-any-link {
    color: -webkit-link;
    text-decoration: underline;
    cursor: auto;
}

Then don't take the parent's color.

.site-map > li {
  color: #f00;
}
<ul class="site-map">
  <li>
    <ul>
      <li><a href="#">I expect this to be black (default color) 1</a></li>
      <li>I expect this to be black (default color)</li>
    </ul>
  <li>First Level Red</li>
</ul>

Upvotes: 1

Quentin
Quentin

Reputation: 943142

The default value for the color property (for most elements) is inherit, which means "Copy the computed value from the parent element".

The outer li has color: red.

The child ul has color: inherit so gets red as the computed value.

The child li also has color: inherit so gets red as the computed value.

Upvotes: 2

Related Questions