user31782
user31782

Reputation: 7589

Understanding working of `div` and `span` elements as children in Descendant selectors

Consider the following code:

<!DOCTYPE html>
<html>
<head>
<style>
li p {
    background-color: yellow;
}
</style>
</head>
<body>

<li>
  <div>
    <p>
       Usual text.
    </p>
  </div>
</li>
</body>
</html>

The Usual text gets a yellow background as expected. Now if I put a block-level element say <div> or <h2> inside the <p> tags something unusual happens. The content between the block-level elements and after block-level elements which is still inside the <p> tags don't get yellow background. E.g. consider the following code,

<!DOCTYPE html>
<html>
<head>
<style>
li p {
    background-color: yellow;
}
</style>
</head>
<body>

<li>
  <div>
    <p>
       Usual text<div>Text Inside Div</div> After div but inside p.
    </p>
  </div>
</li>
</body>
</html>

The problem doesn't appear if i use some inline-element like <span> or <a> inside <p> tags.

  • Why is this behavior shown by only block-level elements?

Upvotes: 0

Views: 71

Answers (1)

Quentin
Quentin

Reputation: 943645

This has nothing to do with CSS. It is a purely HTML issue.

Div elements are not allowed inside P elements.

Additionally, the end tag for the P element is optional and the end of the paragraph will be implied by the Div start tag (rendering the P end tag an orphan).

Upvotes: 1

Related Questions