10. Elements That Cannot Be Nested Arbitrarily
Not every element can contain every other element. HTML defines content models that describe the kinds of content allowed inside an element.
Example 1: Paragraphs and Block-Level Content
A paragraph element accepts phrasing content, not arbitrary sectioning or flow elements. A paragraph is automatically closed by the HTML parser when certain elements that cannot be inside a paragraph begin.
Do not write this when you intend a div inside a paragraph:
<p>
Text before
<div>A separate container</div>
Text after
</p>The browser may close the paragraph before the div and create a different DOM structure than expected. Use separate elements instead:
<p>Text before the container.</p>
<div>A separate container</div>
<p>Text after the container.</p>Example 2: Links Inside Links
An anchor element must not contain another anchor element or other interactive descendants that violate its content model.
Incorrect:
<a href="/courses">
Browse courses
<a href="/html">HTML course</a>
</a>Correct:
<p>
<a href="/courses">Browse all courses</a>
or
<a href="/html">view the HTML course</a>.
</p>Example 3: Lists
List items belong inside list containers such as <ul> or <ol>.
Correct:
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>A browser may attempt to repair invalid list markup, but relying on automatic correction makes code harder to understand and maintain.
Example 4: Table Structure
Table rows and cells must follow the table content model. Use table row elements inside the appropriate table section or table structure.
<table>
<thead>
<tr>
<th scope="col">Course</th>
<th scope="col">Level</th>
</tr>
</thead>
<tbody>
<tr>
<td>HTML5 Mastery</td>
<td>Beginner</td>
</tr>
</tbody>
</table>Use the content model for the specific element you are writing. The HTML standard defines which children are permitted, so visual appearance alone is not enough to determine whether nesting is valid.