HTML · Unit 2: Images and page structure · Lesson 2 of 5
Nesting and indentation
Elements can contain other elements.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
Elements can contain other elements. The outer one is the parent and the inner ones are its children. A list is the parent of its items.
Always close the most recently opened element first, like boxes packed inside boxes.
Indent children by two spaces. The browser ignores the spaces, but people reading your code can see the structure at a glance.
Worked example
HTML
<ul>
<li>Fruit
<ul>
<li>Apples</li>
<li>Pears</li>
</ul>
</li>
<li>Bread</li>
</ul>
The inner list sits inside the Fruit item, so it closes before that item's </li>.
Key terms
- Nesting
- Putting elements inside other elements. Close the most recently opened element first.
Practise it in Code Academy
It has 4 exercises (multiple choice, fix the broken code and write code from a prompt) and takes about 6 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.