2
<!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 Answers2

5

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>
connexo
  • 53,704
  • 14
  • 91
  • 128
  • Is it a rule that it cannot contain it? –  Oct 21 '21 at 11:31
  • It is a rule. From the [p element specs](https://html.spec.whatwg.org/multipage/grouping-content.html#the-p-element): "A p element's end tag can be omitted if the p element is immediately followed by ... , h2 ...". That is, when the parser finds the `

    ` tag after an opening `

    ` tag, it considers the `

    ` tag to be closed without the explicit ending tag.

    – Dym Oct 21 '21 at 12:12
2

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?

l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • `

    ` is a **block level**, not an inline one. Of course, you may change its display type through CSS.

    – Dym Oct 21 '21 at 12:01
  • How can i change –  Oct 21 '21 at 12:09
  • To be clearer, you may change the `

    ` display type to 'inline', but this would not change the behaviour of `

    ` followed by `

    ` or other block level elements. If you can, you may use it the other way round: put the `

    ` tag inside the `

    ` tag, although I would reccomend to use other inline tags for this purpose. The heading tags may be composed with more structured elements. It is not only to indicate that the text is a heading. For example: `

    This is an emphasized and
    two lines red heading

    `
    – Dym Oct 21 '21 at 12:25