An HTML document is like a big family tree, with parents, siblings, children, ancestors, and descendants.
It comes from the ability to nest HTML elements within one another.
Nesting
Let’s write a simple paragraph and enhance it by differentiating parts of the text, by inserting two inline elements:
Sir Alex Ferguson once said about Filipo Inzaghi: "That lad must have been born offside."
.
In this setup:
- the
<strong>
element gives the words “Alex Ferguson” more importance - the
<q>
marks his quote about Inzaghi
The fact that <strong>
is displayed in bold is only the browser’s default behavior. Remember that you have to choose HTML elements according to their meaning, not how they look like.
In this case:
<p>
is the parent element of<strong>
and<q>
<strong>
and<q>
are child elements of<p>
<strong>
and<q>
are sibling elements
Order
How nesting works depends on the location of opening and closing tags.
Because an HTML element comprises an opening tag, a closing tag, and everything in between, a child element must be closed before closing the parent element.
Because the <strong>
was opened after the <p>
(and is thus considered a child of <p>
), the <strong>
element must be closed before its parent <p>
.
Depth
Because child elements can themselves contain other child elements, it’s possible to write a deeper hierarchy within an HTML document.
Our above paragraph could be part of a blog article:
Famous football quotes
Sir Alex Ferguson once said about Filipo Inzaghi:"That lad must have been born offside"
.
When criticized by John Carew, Zlatan Ibrahimovic replied: "What Carew does with a football, I can do with an orange"
.
George Best replied "I spent a lot of money on booze, birds and fast cars. The rest I just squandered"
when asked about his lifestyle.
In this setup:
<article>
is the ancestor of every other element<article>
is the parent of the<h1>
and the 3<p>
<h1>
and the 3<p>
are siblings- each
<p>
is the parent of the<strong>
and<q>
they contain - every
<h1>
,<p>
,<strong>
and<q>
are all descendants of<article>
The family tree analogy still applies when traversing several layers of HTML nesting:
- a descendant of element X is any element contained within X
- a child is just a direct descendant
- an ancestor of element Y is any element that contains Y
- the parent is just the first direct ancestor
- a sibling of element X is any element which has the same parent
Block and inline nesting
Block elements can contain either block or inline elements.
However, inline elements can only contain other inline elements 1.
Just remember ancestor/descendant, parent/child, and siblings. This hierarchy will be useful in CSS.
-
the link element
<a>
is the only exception. ↩