Web Foundations

HTML Nesting Rules

Valid nesting, inline vs block elements, and content models.

Advertisement

HTML Nesting Rules

Valid nesting, inline vs block elements, and content models.

Overview

Proper nesting ensures valid, accessible HTML.

Key Concepts

  • Nesting Rules — Which elements can contain others
  • Content Models — What content is allowed
  • Inline Elements — Flow content within text
  • Block Elements — Structural content
  • Phrasing Content — Text-level content

Code Examples

<!-- Valid nesting -->
<div>
  <p>
    <strong>Bold text</strong>
    <em>Italic text</em>
  </p>
</div>

<!-- Invalid nesting (don't do this!) -->
<!-- <p><div>Invalid</div></p> -->

<!-- Lists must contain list items -->
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<!-- Table structure -->
<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
    </tr>
  </tbody>
</table>

<!-- Forms have specific rules -->
<form>
  <fieldset>
    <legend>Personal Info</legend>
    <label for="name">Name:</label>
    <input type="text" id="name">
  </fieldset>
</form>

<!-- Description list -->
<dl>
  <dt>HTML</dt>
  <dd>HyperText Markup Language</dd>
  <dt>CSS</dt>
  <dd>Cascading Style Sheets</dd>
</dl>

<!-- Figure and figcaption -->
<figure>
  <img src="image.jpg" alt="Description">
  <figcaption>Caption text</figcaption>
</figure>

<script>
// Check nesting validity
function isValidNesting(parent, child) {
  const invalidCombinations = {
    'p': ['div', 'section', 'article', 'nav', 'header', 'footer', 'table', 'ul', 'ol', 'dl', 'form', 'fieldset'],
    'span': ['div', 'p', 'section', 'article'],
    'a': ['a'], // No nested links
    'button': ['button', 'a'],
    'label': ['label']
  };
  
  return !invalidCombinations[parent]?.includes(child);
}

// Validate document structure
function validateHTML() {
  const issues = [];
  const elements = document.querySelectorAll('*');
  
  elements.forEach(el => {
    const parent = el.parentElement;
    if (parent && !isValidNesting(parent.tagName.toLowerCase(), el.tagName.toLowerCase())) {
      issues.push(`Invalid nesting: <${el.tagName}> inside <${parent.tagName}>`);
    }
  });
  
  return issues;
}
</script>

Practice

Audit a webpage for invalid nesting and fix the issues.

Advertisement