Nesting

Markup has a hierarchy, which creates parent/child relationships between elements. Maintaining an accurate hierarchy is essential for readability and avoiding validation issues.

Nest or not?

Write elements without attributes on one line:

<p>The quick brown fox jumps.</p>

Write elements with attributes nested:

<p class="lead">
    The quick brown fox jumps.
</p>

Write elements with multi-line content nested:

<p>
    The quick brown fox jumps.
    Do or do not — there is no try.
</p>

Single-child nesting

Child elements may be most readable without whitespace. Example:

  • Each line is under 80 characters.
  • Each line is nested less than two levels deeper.
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

A good example of multi-level HTML that still benefits from single-line nesting is anchors within lists:

<ul>
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>

Multi-child nesting

Use a single blank line to break up complex hierarchies. Separate child elements with a single blank line.

<ul>
    <li>
        <h2>Title</h2>
        <p>Lorem ipsum dolor.</p>
    </li>

    <li>
        <h2>Title</h2>
        <p>Lorem ipsum dolor.</p>
    </li>

    <li>
        <h2>Title</h2>
        <p>Lorem ipsum dolor.</p>
    </li>
</ul>

Hybrid nesting

In practice, single-line and multi-line syntaxes are both used. The goal is optimum readability for the given content. This is more important than strictly following a single syntax.

<ul>
    <li>
        <h2>Title</h2>
        <p>Lorem ipsum dolor sit amet.</p>
    </li>

    <li>
        <h2>Title</h2>

        <p class="lede">
            Lorem ipsum dolor sit amet.
        </p>

        <p>
            Nulla facilisi. Duis aliquet egestas purus in blandit.
            Curabitur vulputate, ligula lacinia scelerisque tempor,
            lacus lacus ornare ante, ac egestas est urna sit amet arcu.
        </p>
    </li>

    <li>
        <h2>Title</h2>
        <p>Lorem ipsum dolor sit amet.</p>
    </li>
</ul>

Grouping elements

Complex markup can take hundreds of lines to describe relatively simple content. From an authoring perspective, this can be difficult to scan and read. Adding several line-breaks between large sets of markup improves readability for developers. Whitespace characters are collapsed in HTML so there is no visual output, and the additional bytes are negligible.