Is it valid to have paragraph elements inside of a heading tag in HTML5 (P inside H1)?

Slava Fomin II picture Slava Fomin II · Nov 5, 2013 · Viewed 29.7k times · Source

Is it ok to have paragraph elements inside of a header tags in HTML5?

In other words: is this markup correct in HTML5? What are the drawbacks of using this?

<h1>
    <p class="major">Major part</p>
    <p class="minor">Minor part</p>
</h1>

If not, how can I style this elements with CSS correctly?

Answer

Slava Fomin II picture Slava Fomin II · Nov 5, 2013

Actually, no. This markup is not correct according to W3C. You should avoid using this.

It is stated that the correct content for header elements is a "phrasing content", which is phrasing elements intermixed with normal character data.

In other words you can use the following convenient elements inside of a header tag in HTML5: a, em, strong, code, cite, span, br, img. See the full list here.

The W3C validator will give you the following error if you will try to validate this markup: Element p not allowed as child of element h1 in this context.

The one major drawback of using this markup that you should consider is that Search Engines can incorrectly parse your heading tag and miss important data. So this practice can be bad for SEO.

If you would like a better SEO results it is a good practice to include only textual data inside of a heading elements. But, if you also need to apply some styles, you can use the following markup and CSS:

<h1>
    <span class="major">Major part</span>
    <span class="minor">Minor part</span>
</h1>

<style type="text/css">
    h1 span {
        display: block;
    }
    h1 span.major {
        font-size: 50px;
        font-weight: bold;
    }
    h1 span.minor {
        font-size: 30px;
        font-style: italic;
    }
</style>

See the jsfiddle for this.

As stated before, span tag is perfectly valid inside of a header elements (h1-h6). And you can apply "display: block;" style to it to make it render as a block level element (each on a different line). It will save you a br tag.

Of course you will need to change this CSS selectors according to your use case.

And yes, as @stUrb said it's not semantically correct to use paragraphs inside of a headings. The most important idea behind HTML is that it must be a semantics first, presentation later.