Nesting & Hierarchy Lesson 2 of 7

HTML elements live inside other elements. Learn how parent-child relationships shape the DOM.

HTML 101   DESN 368

Everything Is Inside Something

  • Almost every HTML element either contains other elements β€” or is contained by them
  • This is nesting: how HTML creates structure and hierarchy
  • Think of folders on your computer β€” a folder holds files and other folders, and those hold more
  • Every element has a parent (the element it lives inside) and may have children (elements nested inside it)

Common parent-child relationships:

  • A <ul> contains <li> elements
  • A <div> contains paragraphs and headings
  • A <nav> contains links

The DOM Tree

  • When a browser reads your HTML, it builds an internal model: the Document Object Model (DOM)
  • The DOM is a tree β€” <html> is the root, <head> and <body> are its two main branches
<html>
  <body>
    <section>
      <h1>Jazz Playlist</h1>
      <ul>
        <li>Kind of Blue β€” Miles Davis</li>
        <li>A Love Supreme β€” John Coltrane</li>
        <li>Maiden Voyage β€” Herbie Hancock</li>
      </ul>
    </section>
  </body>
</html>

That structure as a tree:

  • html
    • body
      • section
        • h1
        • ul
          • li (Γ—3)

Key vocabulary:

  • Child β€” an element directly inside another element
  • Sibling β€” an element at the same level, sharing the same parent
  • Above: <h1> and <ul> are siblings β€” both are children of <section>

Rules of Nesting

Open before you close β€” tags must nest properly; never close a parent before closing its children:

<!-- Wrong: p closes before strong -->
<p>The concert was <strong>incredible</p></strong>

<!-- Right: strong closes inside p -->
<p>The concert was <strong>incredible</strong>.</p>

Indent to show structure β€” browsers ignore whitespace, but humans depend on it:

  • Use 2 or 4 spaces consistently
  • This is the single most important habit for readable HTML
<!-- Hard to read β€” no indentation -->
<article><h2>The Record Store</h2><p>Vinyl only.</p><ul><li>Jazz</li><li>Soul</li></ul></article>

<!-- Easy to read β€” proper indentation -->
<article>
  <h2>The Record Store</h2>
  <p>Vinyl only. No streaming.</p>
  <ul>
    <li>Jazz</li>
    <li>Soul</li>
  </ul>
</article>

Siblings example β€” three <a> elements, all children of <nav>:

<nav>
  <a href="/">Home</a>       <!-- child of nav, sibling of the other two -->
  <a href="/work">Work</a>   <!-- child of nav, sibling of the other two -->
  <a href="/about">About</a> <!-- child of nav, sibling of the other two -->
</nav>

Designer Note

  • Visual hierarchy in design and structural hierarchy in HTML reinforce each other
  • A heading that’s visually β€œinside” a section should be structurally inside it too
  • When your HTML structure matches your design hierarchy, the code is easier to maintain, style, and hand off