Use quote marks to find an "exact phrase"

Print version

print icon

27: Tidy code

A few basics to make life easier

Time to pause for a word about laying out your HTML and CSS. What you read here may at first seem trivial, but it will help you greatly as your web skills progress. Get in the habit, from the very beginning, of commenting and laying our your code neatly.



Commenting means keeping notes. Write comments in your code so that when you revisit it you can be reminded of what you had in mind at the time – it is very easy to forget when the code gets more complicated. It's a good habit that can save you much headscratching. Comments are not shown by the browser.

Start each comment with  <!--  and finish it with  --> . Use at least two dashes either side.

<!-- your html comment goes in here -->

Have a look at the comment at the bottom of the illustration (<!-- pairedimageleft -->). 'Div closing' comments like this help ensure that each div doesn't lack a closing tag, and that there are no surplus closing tags. This sort of error is very easy to make.


Lay out your code in a neat, organised, way. This is not just for aesthetics – it makes it much easier for you or others to make sense of your code, and you'll certainly appreciate it screenshot of part of html file showing how tidy it is when it comes time to find an error.

Have a look at the illustration of a chunk of code from this site. Note how some lines are indented, some more than others. Child elements are indented, grandchildren moreso.

You'll have to decide if you like your closing tags on the same line or on the next line. You can see that I like to have my paragraph closing tags on a new line, but that's just my preference.

You may have to experiment for a while to find a system that works for you, but once you've found it, be consistent. Line things up, indent things the same distance all the way through, whatever. A little OCD goes a long way here!

The vertical lines are handy for lining things up, such as the opening and closing tags of elements. These are a feature of Notepad++, which I use and recommend.



Commenting in the CSS is no less important than it is with the HTML, but it is done differently. This is how to comment in CSS:

/*  your css comment goes in here  */

Tidy CSS

Even more than your HTML, your CSS can become very unruly. You'll need to work out a way to keep your CSS workable as it accumulates. You may wish to consider the following system: