user31782 February 2016

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?

Answers


Quentin February 2016

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).

Post Status

Asked in February 2016
Viewed 3,974 times
Voted 11
Answered 1 times

Search




Leave an answer