htmlcsscss-selectorscss-cascade

CSS Cascading (Descendant) style


I read about descendant selectors in CSS but can't get it to work:

<!DOCTYPE html>
<html>
<head>
<style>
.c1 div { background-color:red;}
h1 {color: #00b339}
</style>
</head>
<body>
<h1>Demo of the descendant selector</h1>
<p class="c1">Outer paragraph <div class="c2">Inside nested element</div></p>
</body>
</html>

In the style seclector there's a space between the class .c1 and the inner div If I replace that space by a comma, style selector definition works like an OR and all class "c1" and all div elements are affected. But with that space nothing happens to the inner div element. Goal is to apply the style to Inside nested element only.

No matter if I construct that descendance by class or html type definition.

What am I doing wrong? (I'm testing a local file with a current chrome browser on win11)


Solution

  • https://www.w3.org/TR/html401/struct/text.html

    The P element represents a paragraph. It cannot contain block-level elements (including P itself).

    When you inspect the element in DevTools, you will notice that the browser closed the p tag before opening the div tag to avoid having the div inside the p tag. And after the closing tag of div, it opens an empty p element.

    <p class="c1">Outer paragraph</p>
    <div class="c2">Inside nested element</div>
    <p></p>
    

    You cannot avoid this rule, and you shouldn't since a paragraph's purpose is to represent paragraphs of text.