πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

HTML Nesting Rules

Web Foundations🟒 Free Lesson

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


<div>
  <p>
    <strong>Bold text</strong>
    <em>Italic text</em>
  </p>
</div>





<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>


<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>


<form>
  <fieldset>
    <legend>Personal Info</legend>
    <label for="name">Name:</label>
    <input type="text" id="name">
  </fieldset>
</form>


<dl>
  <dt>HTML</dt>
  <dd>HyperText Markup Language</dd>
  <dt>CSS</dt>
  <dd>Cascading Style Sheets</dd>
</dl>


<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.

⭐

Premium Content

HTML Nesting Rules

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement