#2: All About Nesting
In the last tutorial we learned about HTML elements and how we can use them in a simple way. In this tutorial we’re going to talk about nesting those elements.
What is Nesting?
When we put one HTML element inside another, that’s called nesting, a bit like the way Russian dolls nest into one another.
Here’s a paragraph, just like we looked at last time:
<p>Here’s a nice long sentence all about birds and their lovely, fluffy feathers.</p>
Now let’s put a <strong>
tag inside the <p>
, around the middle bit of the sentence:
<p>Here’s a nice long sentence <strong>all about birds</strong> and their lovely, fluffy feathers.</p>
Exercise 1
Fork this pen on CodePen. See how the words inside the <strong>
tags look bolder? Now change the sentence so that the first five words are strong instead.
So there we nested the <strong>
inside the <p>
. And you can do the same with all kinds of HTML elements. Here’s an emphasis tag <em>
(remember that one?) nested within a <h3>
.
<h3>This is a <em>brilliant</em> title!</h3>
By the way: It doesn’t matter how we write the code above, as long as it’s in the right order. Your browser reads this code exactly the same:
<h3>
This is a
<em>brilliant</em>
title!
</h3>
Some elements are supposed to be nested. For example, here we have an “ordered list” element (a list of things in order): <ol>
. An ordered list needs to have “list items” which look like this: <li>
. We can have as many list items nested in the ordered list as we like:
<ol>
<li>Milk</li>
<li>Cheese</li>
<li>Chocolate spread</li>
<li>Bread</li>
<li>Dog food</li>
</ol>
Our browser sees this HTML code and makes it look like this:
The <ol>
is empty without the <li>
tags, and the <li>
tags can’t live without the <ol>
.
Exercise 2
Fork the pen above and switch the <ol>
element for a <ul>
. A <ul>
element is an unordered list–what difference do you think it will make?
More Nesting!
We don’t have to stop at nesting just one element inside another; we can nest as many times as we want!
Warning! We must always make sure that we nest things properly. Just like the Russian dolls we have to nest things neatly, without tangling the tags, otherwise our code might break.
Exercise 3
What’s wrong with this code, which nests a <span>
(new element for you) inside a <h3>
?
<h1>Here’s a heading about something <span>very important</h1></span>
Create a new pen, give it the title “Tutorial #2, Exercise 3” and save what you think the correct code should be.
Conclusion
You’ve reached the end of the second tutorial, nice one! You now know how to nest HTML elements. You’ve also learned that some elements need to be nested to be complete. In the nest tutorial (sorry, I mean next tutorial ☺️) we’ll learn about some important HTML elements which help us organise our web pages.