Headings in HTML


Headings

So far we’ve covered paragraphs and line breaks… but in a long document, we probably want more structure than that. How do we create section headings?

The h Elements

There are six levels of heading elements: h1, h2, h3, h4, h5, and h6. These block elements tell the browser to set off the heading from the rest of the text. The h1 heading level is the most important heading, while the h6 level is the least important.

Most browsers display headings in bold, with h1 the largest and h6 the smallest.

Example 2.6. Headings

<h1>Heading 1</h1>

<h2>Heading 2</h2>

<h3>Heading 3</h3>

<h4>Heading 4</h4>

<h5>Heading 5</h5>

<h6>Heading 6</h6>

Like the paragraph element p, the heading elements are block elements. Each matched set of heading elements creates a new block, automatically separated from other blocks with line breaks.

Mangled Headings

In “Paragraph Breaks”, we discussed the consequences of failing to close your open <p> tags. This is even more important for heading elements.

Example 2.7. Mangled Heading and Text

<h1>STAVE I: MARLEY'S GHOST

MARLEY was dead: to begin with. There is no doubt
whatever about that. The register of his burial was
signed by the clergyman, the clerk, the undertaker,
and the chief mourner. Scrooge signed it: and
Scrooge's name was good upon 'Change, for anything he
chose to put his hand to. Old Marley was as dead as a
door-nail.

Whoops! If you view the resulting web page, you’ll see that the h1 element’s oversized, bold font has spilled over onto the rest of the text. The browser has no indication where the h1 element is supposed to end, and so it interprets the h1 element as enclosing everything else on the page.

Let’s fix this by closing the open <h1> tag. We’ll put the text in its own HTML paragraph for good measure:

Example 2.8. Proper Heading and Text

<h1>STAVE I: MARLEY'S GHOST</h1>
<p>
  MARLEY was dead: to begin with. There is no doubt
  whatever about that. The register of his burial was
  signed by the clergyman, the clerk, the undertaker,
  and the chief mourner. Scrooge signed it: and
  Scrooge's name was good upon 'Change, for anything he
  chose to put his hand to. Old Marley was as dead as a
  door-nail.
</p>

The heading and paragraph are now properly separated.

Leave a comment