12 Principles For Keeping Your Code Clean

Advertisement

Beautiful HTML is the foundation of a beautiful website. When I teach people about CSS, I always begin by telling them that good CSS can only exist with equally good HTML markup. A house is only as strong as its foundation, right? The advantages of clean, semantic HTML are many, yet so many websites suffer from poorly written markup.

Let’s take a look at some poorly written HTML, discuss its problems, and then whip it into shape! Bear in mind, we are not passing any judgment on the content or design of this page, only the markup that builds it. If you are interested, take a peek at the bad code1 and the good code2 before we start so you can see the big picture. Now let’s start right at the top.

1. Strict DOCTYPE

If we are going to do this, let’s just do it right. No need for a discussion about whether to use HTML 4.01 or XHTML 1.0: both of them offer a strict version that will keep us nice and honest as we write our code.

strict doctype example

Our code doesn’t use any tables for layout anyway (nice!), so there really is no need for a transitional DOCTYPE.

Resources:

2. Character set & encoding characters

In our <head> section, the very first thing should be the declaration of our character set. We’re using UTF-8 here, which is swell, but it’s listed after our <title>. Let’s go ahead and move it up so that the browser knows what character set it’s dealing with before it starts reading any content at all.

character example

While we’re talking about characters, let’s go ahead and make sure any funny characters we are using are properly encoded. We have an ampersand in our title. To avoid any possible misinterpretation of that, we’ll convert it to &amp; instead.

Resources:

3. Proper indentation

All right, we are about three lines in and I’m already annoyed by the lack of indentation. Indentation has no bearing on how the page is rendered, but it has a huge effect on the readability of the code. Standard procedure is to indent one tab (or a few spaces) when you are starting a new element that is a child element of the tag above it. Then move back in a tab when you are closing that element.

indentation example

Indentation rules are far from set in stone; feel free to invent your own system. But I recommend being consistent with whatever you choose. Nicely indented markup goes a long way in beautifying your code and making it easy to read and jump around in.

Resources:

4. Keep your CSS and JavaScript external

We have some CSS that has snuck into our <head> section. This is a grievous foul because not only does it muddy our markup but it can only apply to this single HTML page. Keeping your CSS files separate means that future pages can link to them and use the same code, so changing the design on multiple pages becomes easy.

external example

This may have happened as a “quick fix” at some point, which is understandable and happens to all of us, but let’s get that moved to a more appropriate place in an external file. There is no JavaScript in our head section, but the same goes for that.

5. Nest your tags properly

The title of our site, “My Cat Site,” is properly inside <h1> tags, which makes perfect sense. And as per the norm, the title is a link to the home page. However, the anchor link, <a>, wraps the header tags. Easy mistake. Most browsers will handle it fine, but technically it’s a no-no. An anchor link is an “inline” element, and header tags are “block” elements. Blocks shouldn’t go inside inline elements. It’s like crossing the streams in Ghostbusters. It’s just not a good idea.

nesting example

6. Eliminate unnecessary divs

I don’t know who first coined it, but I love the term “divitis,” which refers to the overuse of divs in HTML markup. Sometime during the learning stages of Web design, people learn how to wrap elements in a div so that they can target them with CSS and apply styling. This leads to a proliferation of the div element and to their being used far too liberally in unnecessary places.

divitis example

In our example, we have a div (“topNav”) that wraps an unordered list (“bigBarNavigation”). Both divs and unordered lists are block-level elements. There really is no need whatsoever for the <ul> to be wrapped in a div; anything you can do with that div you can do with the <ul>.

Resources:

7. Use better naming conventions

This is a good time to bring up naming conventions, as we have just talked about that unordered list with an id of “bigBarNavigation.” The “Navigation” part makes sense, because it’s describing the content that the list contains, but “big” and “Bar” describe the design not the content. It might make sense right now because the menu is a big bar, but if you change the design of the website (and, say, change the website navigation to a vertical style), that id name will be confusing and irrelevant.

naming conventions example

Good class and id names are things like “mainNav,” “subNav,” “sidebar,” “footer,” “metaData,” things that describe the content they contain. Bad class and id names are things that describe the design, like “bigBoldHeader,” “leftSidebar,” and “roundedBox.”

8. Leave typography to the CSS

The design of our menu calls for all-caps text. We just dig how that looks, and more power to us. We have achieved this by putting the text in all-caps, which of course works; but for better, future extensibility, we should abstract typographic choices like this one to the CSS. We can easily target this text and turn it to all-caps with {text-transform: uppercase}. This means that down the road, if that all-caps look loses its charm, we can make one little change in the CSS to change it to regular lowercase text.

typography example

9. Class/id the <body>

By “class the body,” I literally mean apply a class to the body, like <body class=”blogLayout”>. Why? I can see two things going on in this code that lead me to believe that this page has a layout that is different than other pages on the website. One, the main content div is id’d “mainContent-500.” Seems like someone had a “mainContent” div at one point and then needed to alter its size later on and, to do so, created a brand new id. I’m guessing it was to make it larger, because further in the code we see <class=”narrowSidebar”> applied to the sidebar, and we can infer that that was added to slim down the sidebar from its normal size.

This isn’t a very good long-term solution for alternate layouts. Instead, we should apply a class name to the body as suggested above. That will allow us to target both the “mainContent” and “sidebar” divs uniquely without the need for fancy new names or class additions.

body class example

Having unique class and id names for the body is very powerful and has many more uses than just for alternate layouts. Because every bit of page content lies in the “body” tag, you can uniquely target anything on any page with that hook; particularly useful for things like navigation and indicating current navigation, since you’ll know exactly what page you are on with that unique body class.

Resources:

10. Validate

Kind of goes without saying, but you should run your code through the ol’ validator machine to pick up small mistakes. Sometimes the mistakes will have no bearing on how the page renders, but some mistakes certainly will. Validated code is certain to outlive non-validated code.

validation example

If for no other reason, seeing that green text on the W3C validator tool just makes you feel good inside.

Resources:

11. Logical ordering

If it is at all possible, keeping the sections of your website in a logical order is best. Notice how the footer section lies above the sidebar in our code. This may be because it works best for the design of the website to keep that information just after the main content and out of the sidebar. Understandable, but if there is any way to get that footer markup down to be the last thing on the page and then use some kind of layout or positioning technique to visually put it where you need it, that is better.

order example

12. Just do what you can

We’ve covered a lot here, and this is a great start to writing cleaner HTML, but there is so much more. When starting from scratch, all of this seems much easier. When trying to fix existing code, it feels a lot more difficult. You can get bogged down in a CMS that is forcing bad markup on you. Or, there could be just so many pages on your website that it’s hard to think of even where to begin. That’s OK! The important thing is that you learn how to write good HTML and that you stick with it.

The next time you write HTML, be it a small chunk in a huge website, or the beginning of a fresh new project, just do what you can to make it right.

order example

(al)

Footnotes

  1. 1 http://www.smashingmagazine.com/images/principles-keep-code-clean/CodeExamples/bad.html.txt
  2. 2 http://www.smashingmagazine.com/images/principles-keep-code-clean/CodeExamples/good.html.txt
  3. 3 http://www.w3.org/QA/2002/04/valid-dtd-list.html
  4. 4 http://www.alistapart.com/stories/doctype/
  5. 5 http://www.456bereastreet.com/archive/200609/no_more_transitional_doctypes_please/
  6. 6 http://en.wikipedia.org/wiki/UTF-8
  7. 7 http://www.cs.tut.fi/~jkorpela/chars.html
  8. 8 http://www.ascii-code.com/
  9. 9 http://www.w3.org/People/Raggett/tidy/
  10. 10 http://csscreator.com/?q=divitis
  11. 11 http://css-tricks.com/id-your-body-for-greater-css-control-and-specificity/
  12. 12 http://www.37signals.com/svn/archives2/case_study_reusing_styles_with_a_body_class.php
  13. 13 http://validator.w3.org/
  14. 14 http://xhtml-css.com/
  15. 15 http://freesitevalidator.com/

↑ Back to top Tweet itShare on Facebook

I create websites and help others create better websites through writing and speaking. I consider myself a lucky man for getting to work in such a fun and rewarding field.

Advertisement
  1. 1

    great post, thanks :)

    0
  2. 202

    Great post!

    Thanx…

    0
  3. 403

    The XML prolog in the ‘good’ HTML triggers browsers (even modern ones) into quirks mode. Not what you want. Since the defaults are used (utf-8, stand alone) it can be omitted without problems.

    0
  4. 604

    A nice post

    0
  5. 805

    good things haha

    0
  6. 1006

    Decent enough article to state guidelines for common practice. Nothing too intense here, just a “hey, make sure you cross your t’s and dot your i’s”

    0
  7. 1207

    Nice list, except I must disagree with point #8. if you use css to change the capitalization, then you go to select/cut/paste the text in the web page, the pasted text will be exactly as it is in the HTML, not as instructed by the css rule(s). This is a deception.

    0
  8. 1408

    It’s interesting to see the persnickety assumption from many of the posters here that someone who primarily programs automatically grasps the ins and outs of semantic xhtml and css. I’ve worked with dozens of so-called “hardcore” programmers…many who have been coding website back-end functionality for years…not a one knew/knows all of the basic rules outlined in this article. They couldn’t care less about the front-end, as long as it works. Try to teach a .net developer to ditch the design view and see how far you get.

    Also – I’ve been trying to hire two new people for months. I’ve conducted dozens of interviews, and each person claims to have at least a decade of experience in web development. The first four questions I ask everyone:

    1. Which xhtml tags would you use to wrap these elements, which will be children of the body tag? (on a whiteboard I write ‘About Our Company’, and then on a subsequent line ‘Paragraph text’)

    2. What is the purpose of the DOCTYPE definition?

    3. You are handed an approved creative comp from one of our designers. When you open the PSD, you notice that they decided to include meaningful header text for each page as part of a stylized banner image. How will you construct this element without changing the design?

    4. What is n-tier (or three-tier) architecture?

    Not a single person has answered any of these questions correctly.

    0
  9. 1609

    Hi Chris Coyier,
    Very good post, pretty helpful…

    0
  10. 1810

    Those seem like pretty reasonable principles that I don’t break to often. Thanks for the list.

    0
  11. 2011

    If anything…this has confirmed that clean coding is essential, and not difficult!
    Thanks!

    0
  12. 2212
  13. 2413

    it’s really helpful to us……

    0
  14. 2614

    yes its really helpfull for coding

    0
  15. 2815

    Really helpful principles, any more?

    0
  16. 3016

    Hi there, If you don’t like topics with many links, just delete this topic.
    Thankyou.

    0
  17. 3217

    Nice tips

    0
  18. 3418

    i will do all what i can do !
    i love web design !

    0
  19. 3619

    I’m no expert at this hense why i’m here but the first thing I noticed when viewing the source code on this page is it’s using Transitional as opposed to Strict???

    0
  20. 3820

    I want to quote your post in my blog. It can?
    And you et an account on Twitter?

    0
  21. 4021

    Good article. I typically use CSS tools such as the validator.w3.org, cleancss.com or cssanalyzer.com, to checking that CSS code I created, it’s very useful tools. Maybe you have a similar validator tools, which apply the 12 principle as above? Thanks

    0
  22. 4222

    Very nice article for classroom lessons and newbies! Anything for pros?

    -1
  23. 4423

    I realized that strict code and markup that completely validates appeals mostly to fresh web designers who are truly looking for direction (normally thinking that there is a winning particular way of doing things on the web.)

    Back to the real world, where you have websites that really serve others out there, its completely unconceivable to think that code will always validate 100%. Besides, clean code should by no means stand in the way of great designs or purpose the site was designed to fulfill.

    Well, I jacked you out, right?

    0
  24. 4624

    Correct.
    Also text-transform doesn’t work with other international languages such as Arabic or Japanese. Big problem to rely on when you have a multi-lingual site.

    -1
  25. 4825

    Great article. I’ve been following some of your articles online and thought I’d chime in with my support for you work! Cheers

    Jeff

    0
  26. 5026

    It’s very useful.Thank you !

    0
  27. 5227

    Robert {Bryan} Anthony

    February 23, 2011 9:25 am

    Swell Info Here, Chris!

    I’m 20/800 blind attempting code for my FBML, Custom Site Editors, and other pages requiring code. I’m a NEWBIE at the code writing, just enough to get myself into some trouble and wondering how in the world I’m going to FIX what I just messed up!

    My MAC reads to me. However, it’s a NIGHTMARE to get it to read Code for me. Just doesn’t work!!!

    I look forward to discovering more about HOW to write clean code, once I get a better grasp on the concepts, and apply it to my websites and pages. Thank you for the vital info!

    “May you walk in freedom…” – Psalm 119:45
    MeetRBryanAnthony.com

    1
  28. 5428

    it‘s so usfull.thank you!

    0
  29. 5629

    Breno Martinusso

    May 20, 2011 6:11 am

    I can translate this post in Portuguese and put on my blog? Obviously with that reference.

    0
  30. 5830

    Thanks,
    This is very useful stuff for a novice like myself, I have found myself making these same mistakes, but reading this article has helped me to look at coding a lot more carefully now.

    0
  31. 6031

    You said the first rulel to use “Strict” doctype. But your web site using Transitional …whats this baby…

    0
  32. 6232

    The writer of the post doesn’t own the website. xD They contribute articles to it. If you check Chris’s actual website you’ll probably find that he actually does use the correct doctype.

    0
  33. 6433

    This is pretty good. I liked it. Kudos, Chris.

    0
  34. 6634

    Smashing Mag, I love you for this..!

    0
  35. 6835

    Interesting staff. Big-ups!!!

    0
  36. 7036

    Stuart Blessman

    July 26, 2013 8:38 am

    Is there an updated version of this? Looking for resources while planning a relaunch of an ecommerce site and a few article heavy sites.

    1
  37. 7237

    “Our code doesn’t use any tables for layout anyway”!

    This is just silly. Further up we have somebody saying that you are lazy and unprofessional if you use tables.

    The fact is that if you are using “CSS” rather than tables for tabular data, then a worse description in fact fits you.

    0
  38. 7438

    Yeah, but that’s not all, when using “margin:0 auto;”. One must also specify a fixed width of pixels or percentage in order for it to work, and the width must really create the space of the left and right margins of the styled element with equal values, meaning that both must have, for example, 200px. :)
    All in all, I too believe is the best way to center elements within other elements or in a document, in a web page.

    -2

↑ Back to top