0

Here is the code

body {
  color: purple;
}

p {
  color: blue;
}
<body>
    <p> 
        <h1>Hello</h1>
    </p>

    <h1>Hello</h1>
</body>

Now problem here is that h1 does not inherit the color of element p which is its nearest parent. I read that if color is not given, then its default value is inherit. So, first h1 should be blue. So, what is happening here ?

user9026
  • 683
  • 2
  • 8
  • 16

1 Answers1

5

What is happening is caused by a problem with the HTML.

A p element cannot contain an h1 element so the system has closed the p element just before the h1 element. Hence the h1 element takes on the color of its nearest ancestor which has a color set and that is body in this case.

Try instead a legal bit of HTML, where the p is replaced with a div:

body {
  color: purple;
}

div {
  color: blue;
}
<body>
  <div>

    <h1>Hello</h1>
  </div>
</body>
A Haworth
  • 22,302
  • 3
  • 8
  • 12
  • 2
    @user9026 You might find this useful: [Is there a list of HTML5 elements that can be nested inside other elements?](https://stackoverflow.com/q/56498472/1115360) – Andrew Morton Nov 21 '21 at 12:15
  • @andrew-morton Thanks. I did not know that this is an illegal way of using HTML – user9026 Nov 21 '21 at 12:25
  • When I checked my `HTML` file in [W3C Validation Service](https://validator.w3.org/) site, I do get error `No p element in scope but a p end tag seen`. So, you guys are right. Thanks again. – user9026 Nov 21 '21 at 12:32