0

i study css, but child selector is not work well.

<style>
    header > p{
        color: red;
    }
</style>
<header>
    <p>
        aaa
        <div>bbb</div>
    </p>
</header>

it works only aaa is red, bbb is not apply but

 <style>
    header > div{
        color: red;
    }
</style>
<header>
    <div>
        aaa
        <p>bbb</p>
    </div>
</header>

it apply aaa and bbb why do this work?

D.A.KANG
  • 265
  • 2
  • 4
  • 12
  • 2
    Because `color` is an inheritable style property. Style properties related to fonts are typically inheritable. See [Inheritence](https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance) – Ouroborus Jan 27 '22 at 01:28
  • I know about inheritance. But then, isn't it that child selectors can't be used? As far as I know, child selectors only apply to children and not to children of children. – D.A.KANG Jan 27 '22 at 01:41
  • They do only apply to only to children. However, inherited style properties have `inherit` as their default value and so inherit from their parent. (Had your HTML been valid in your first example, it would have behaved the same way as your second example. Of course the answer below is correct in this particular case where your HTML is incorrect.) – Ouroborus Jan 27 '22 at 02:30

1 Answers1

1

This is because your first example is not valid HTML

According to the specification, <p> elements don't allow block elements like <div> inside it.

So the browser (using the tag omition rules), closes the <p> element before the <div> and then opens a new <p> when encounter the </p> closure.

You can see it yourself in the browser console. Also some tools will point you that this is not a valid arrangement of DOM elements.

If you change the <div> to a <span> you will see that it takes the red color as you expect

enter image description here

You can read more here in this complete answer: https://stackoverflow.com/a/10763952/17537072

Daniel Cruz
  • 1,437
  • 3
  • 5
  • 19