Topic 7 of 41
Nesting Tags
Overview
HTML is a hierarchical language. This means tags are put *inside* other tags. This is called 'Nesting'.
Nesting is how you build complex layouts. A `<p>` tag inside a `<div>` tag inside a `<body>` tag. Think of it exactly like Russian nesting dolls (Matryoshka dolls) or boxes inside of boxes.
Syntax
When you nest elements, they form a family tree. The element on the outside is the 'Parent'. The element inside is the 'Child'. Elements next to each other inside the same parent are 'Siblings'.
The Parent/Child Relationship
html
<div> <!-- Parent -->
<h1>Title</h1> <!-- Child (Sibling to the p tag) -->
<p>Text</p> <!-- Child (Sibling to the h1 tag) -->
</div>This is the most common mistake beginners make: You MUST close tags in the reverse order that you opened them. The last tag opened must be the first tag closed. (LIFO - Last In, First Out).
The Rule of Closing Orders
html
<!-- ✅ CORRECT: <strong> opened last, so it closes first. -->
<p>This is <strong>important</strong> text.</p>
<!-- ❌ WRONG: Intersecting tags! This will break your layout. -->
<p>This is <strong>important</p> text.</strong>Common Pitfalls
- Failing to indent properly leads to 'spaghetti code' where you can't tell which tag belongs to which parent, making it impossible to find missing closing tags.
- As mentioned before, you cannot nest Block elements inside Inline elements. (e.g., You can't put a <div> inside a <span>).
Real-World Example
Proper indentation makes nesting easy to read:
example
html
<!--
Always use the Tab key to indent child elements.
This makes the 'family tree' visually obvious.
-->
<article class="blog-post">
<header>
<h2>Understanding Nesting</h2>
<div class="author-info">
<img src="avatar.jpg" alt="Author" />
<span>Kartik Rai</span>
</div>
</header>
<p>Content goes here...</p>
</article>