Why css is not being applied on the elements with same class?

Viewed 134
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

<style>
    .city
    {
        background-color: black;
        color:blanchedalmond;
    }
</style>

</head>
<body>
    <div class="city">
<h1>Paris</h1>
    </div>
    <p class="city"><h2>Germany</h2></p>
</body>
</html>

I was learning about classes and now I made two html elements with the same class but css is not applied on the p tag.

2 Answers

Because p cannot contain h2.

Check your browser's element inspector. The h2 automatically closes the p element, as a result this is the HTML actually being rendered:

<p class="city"></p>
<h2>Germany</h2>
<p></p>
<p class="city"></p><!-- the closing tag here is automatically added by the browser because the `<h2>` closes a parent `<p>` element -->
<h2>Germany</h2>
<!--the missing opening tag <p> is added by the browser's fault tolerance here --></p>

It's about HTML structure and display:

<h2> should not be inside <p> (You don't need <p> to covert your <h2>)


Display: (style)

<h2> is as a block

<p> is as an inline


HTML structure: (render)

<p><h2>Germany</h2></p>

will be rendered to:

<p class="city"></p>
<h2>Germany</h2>
<p></p>

Trick:

Right click on that element in your browser and Inspect it for see HTML rendered result (very useful for debug)

enter image description here

Read more: How to use an <h2> tag </h2> inside a <p></p> in the middle of a text?

Related