Nesting HTML Tags

How to Nest HTML Tags Correctly

What Does It Mean to Nest HTML Tags?

The easiest way to understand nesting is to think of HTML tags as baskets that hold your content. Your content includes text and images. HTML tags are the baskets around the content. 

If you have a block of text that you want bold, italic and inside a paragraph, you'll have three HTML elements and the text itself.

Example: This is a sentence of text.

Because you want the whole sentence to be bold, you add opening and closing bold tags before and after the text.

<b>This is a sentence of text.</b>

Because you want the sentence to be italics too, the opening and closing italics tag is added before and after the entire block of text.

<i><b>This is a sentence of text.</b></i>

Finally, you add the paragraph tags to complete the nest of tags.

<p><i><b>This is a sentence of text.</b></i></p>

When you nest tags, you close the tags in the opposite order that you opened them. Reading from left to right, the tags are opened: P, I, B. You close them in reverse order: B, I, P.

What If I Don't Want the Entire Sentence Bold?

It's easy to understand nesting when you have an entire sentence that is bold or italic, but what if you only want one or two words to be bold, and another set to be italic? If there is overlap, then you'll need to write the overlapped tag twice:

<p><b>This <i>is</i></b> <i>a sentence</i> of text.</p>

The tags are opened P, B, I. Then I and B are closed; I is re-opened, and then I and P are closed.

The nesting order is correct.

Most beginning web developers don't like to write their sentences like that, because it seems like you're adding extra tags. Most beginners would write:

<p><b>This <i>is</b> a sentence</i> of text.</p>

The tags are opened: P, B, I, but then they are closed B, I, P—in the wrong order.

While this HTML works in many browsers, it is not a good habit to develop. It's invalid XHTML, and some browsers, especially screen readers and cell phones can become confused by the incorrect nesting.

Why Should You Care About Nesting

The number one reason that you should care about nesting is if you're going to use CSS. Cascading Style Sheets rely on tags to be consistently nested within the document so that it can tell where styles begin and end. If you set up a style that should affect all "bold plus italic" text on the page, the incorrect nesting makes it hard for the browser to know where the bold plus italic text ends and where the text is just italic.

Other reasons include accessibility and browser compatibility. If your HTML is incorrectly nested, it won't be as accessible to screen readers and older browsers.

Finally, if you're striving to write completely correct and valid HTML or XHTML, you'll need to use correct nesting. Otherwise, every validator will flag your HTML as incorrect.