Think of an HTML document like a tree – we call it a document tree. It’s a bit like a family tree where elements in the document are like family members. They have ancestors, descendants, parents, children, and siblings in this tree.
Understanding the document tree is essential because CSS selectors rely on it. These selectors help style and design elements on a webpage based on their relationship in the document tree.
Let’s look at an example using a simple HTML document. We’ll skip the <head> part to keep things short:
<body>
<div id="content">
<h1>Heading here</h1>
<p>Lorem ipsum dolor sit amet.</p>
<p>Lorem ipsum dolor <em>sit</em> amet.</p>
<hr>
</div>
<div id="menu">
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</div>
</body>
A diagram of the above HTML document tree would look like this.
Ancestor
Any element that is connected further up the document tree—regardless of how many levels higher—is referred to as an ancestor. An ancestor can be a parent, a grandparent, a great-grandparent, and so on.
The <body> element is the parent element of every other element on the page, as seen in the diagram below.
Descendant
Any element that is connected further down the document tree—regardless of the number of levels—is referred to as a descendent. A descendent can be a child, a grandchild, a great-grandchild, and so on.
All items connected below the element in the diagram below are that’s descendants.
Parent and Child
An element in the document tree that is immediately above to another element is called a parent. The <div> is a parent of the <ul> in the diagram below.
An element in the document tree that is immediately below to another element is called a child. The <div> is the parent of the <ul> in the diagram below.
Sibling
An element that has the same parent as another element is called a sibling.
Since they all have the same parent the <ul>, the <li>’s in the diagram below are siblings.
In a nutshell, the HTML Document Tree is like a family tree for your webpage. It shows how elements relate to each other, with ancestors above, descendants below, and parents, children, and siblings in between. Grasping this tree structure is crucial because it forms the basis for styling with CSS.
See more: