A Brief Introduction

Writing clean, proper code should be important to you as a developer for more than a few reasons. Namely, the code will be easier for you to read should you have to return to it at a later date. I can’t count how many times I’ve gone back to my own projects, looked at the HTML, and thought “…my God, what have I done?”

Nesting of elements isn’t new to HTML; in fact it’s been around since day one. However, improperly nested code is still quite a common occurrence, and while it may render correctly, it’s not the correct way to do it. In this tutorial, you will learn the proper way of nesting HTML code.

Setup

If you have not already done so, open Visual Studio and start a new web project. If you would rather use your own development environment or text editor, such as notepad, you may set them up at this time.

Step 1.

Take a look at the following (properly) nested code:

As you can see, we first open a div element called “demo”. Then we’ve created another div element directly inside of that called “center”. Next, we’ve opened a paragraph tag appropriately called “paragraph” directly after that. So, in order to nest properly, we need to close our elements in the opposite of the order they were opened. That’s why first we close our paragraph, then our center div, and finally we close our top div.

Step 2.

Let’s look at a horrifically improper nesting using only a div element and a paragraph element:

In the last example, the paragraph element wasn’t nested properly because it was opened within a div, but it was closed outside of it. Any element that has to be contained (nested) within another must be closed within that element as well. If you were to load up the previous code into a browser, with some text in the paragraph tag, you’d probably still be able to see the text. This is because the browser is assuming that you were trying to nest the paragraph element inside of the div, and tries to fix your mistake. However, this brings us to our next point – validation.

The fine folks at the W3C (World Wide Web Consortium) can be considered the HTML police. When a web page is said to “validate”, that means it meets all of the coding standards as set by the W3C. Not nesting your elements properly will ensure that you’re page will never validate, and make it harder for browsers to interpret exactly what you were trying to accomplish in that section of your page. All in all, you want to be writing clean, readable, and more importantly valid code. Proper nesting will help you accomplish this.

A Few Last Words

The important thing to take from today’s tutorial is that anytime you have an HTML element that has another element inside of it, be sure to close the inner element before closing its containing element. This will save you loads of headaches in the future, and make your code easier to read. Remember, the W3C wants your page to be able to validate, and so should you.

Download Source Files