BEST OF

CSS

DESIGN JOBS

FONTS

FREEBIES

Home » CSS

12 Principles For Keeping Your Code Clean

Submitted by admin on Thursday, 13 November 200849 Comments

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. 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.

CleanCode-1 by you.

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.

CleanCode-2 by you.

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.

CleanCode-3 by you.

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.

CleanCode-4 by you.

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.

CleanCode-5 by you.

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.

CleanCode-6 by you.

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.

CleanCode-7 by you.

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.

CleanCode-8 by you.

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.

CleanCode-9 by you.

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.

CleanCode-10 by you.

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.

CleanCode-11 by you.

order example

49 Comments »

  • Volie said:

    it is a great list…!
    let’s do it strict baby ;)

  • Chin said:

    Fantastic post

  • Riccardo said:

    A useful and well written article. Thanks!

    You also included some great resource links and made me laugh a few times, too! (”It’s like crossing the streams in Ghostbusters. It’s just not a good idea.” Heh!)

  • Carrie ( said:

    What font are you using for the handwritten comments?
    Nice post!

  • CMike Archibald said:

    Great post! I can check 9 out of 10 most of the time, but it did remind my of one small point I’ve been forgetting and that’s to use text-transform: uppercase;

  • Francesco Camarlinghi said:

    Nice post for beginners. Another good principle is to use lists (both ordered and unordered) when possible instead of divs. E.g.: a menu can be done with an ul element as it is a list of links, same goes for a category list, a post list, etc. The list of cats (#12) should have been done in that way too.

    http://www.capkin.us

  • Adam Clark said:

    Lets not forget that properly formatted, streamlined code is also more compact in file size and nicer to the world!

    Excellent article. Well written and presented. It’s about time we had articles of this quality on ultrabilisim. Don’t get me wrong, posts about “The 50 most beautiful this and that” are all well and good for inspiration but articles on good practise are also a great tool to have. Keep up the good work and I hope it helps make the HTML world a cleaner, more logcal place to work in.

  • Hubbers said:

    Excellent article.

  • AL said:

    Awesome post! #5 was an eye opener!

  • george said:

    div in li? you gotta be kidding.

  • Leannekera said:

    As a 5 year CSS bod myself I have to say that this must be the best Smashing article on CSS for beginners I have read to date.

    Good job old chap!

  • Ronald Lokers said:

    Great post, it totally aproves that I work the right way :)

  • Banelicious said:

    Awesome post, really nice to read with some interesting points in it…

  • Aaron said:

    A very usefull article, thanks!

  • Rene Schmidt said:

    Good vibes here

  • Ani López said:

    About ‘11. Logical ordering’
    what you mean by ‘logical order’, visual one? I meam:
    1- Header
    2- Content
    3- Columm
    4- Footer
    this is the order while displaying the web but for SEO purposes (place the main content up as possible in markup) the logical order can be:
    1- Content
    2- Columm
    3- Footer
    4- Header
    Yes, it can confuse a bit while working it but remember that uploading a web to server and make it alive is not the last step, is just the begining of the adventure and search engines are going to crawl your site so better serve it the best way or your work will be for nothing in most of the cases.

  • Shuuun said:

    Jeah, pretty cool!

    All newbies will love this ;)
    I will show this article some of my trainies!

  • Bluens said:

    Thanks man, great article. Saved in my bookmarks…

  • Javi said:

    Basic but nice post.
    Thanks!

  • BWPandas said:

    Great article! Back to basics.

  • h-a-r-v said:

    I agree upon Strict but Transitional may be needed when e.g. using iframes (like Google map). It shall fade into the past when object finally renders properly in most browsers, but not today.. not today.

    And I believe 10. consists 5. (any validation points badly nested tags, right? - of course the rules should be applied while coding - it measures our skill and saves time - but if validation is mentioned I guess it serves a higher purpose than just pointing badly ended tags).

  • Mukesh said:

    It’s nice…….but very difficult to apply STRICT markup……when we are working on CMS’s…………end user doesn’t think about this..

    Well it’s nice post!

    Thanks!

  • MBomnun said:

    Nice post! Thanks.

  • MBomnun said:

    Well explained.. cleared concepts of writing new html code… 10 out of 10 marks…

  • Neil said:

    Completely disagree with 4, I’m getting very tired of sites loading without styles or JavaScript whenever there’s a glitch with the connection! The correct approach would be to keep the important code in the header (from a server side include) and use an external file for all the extras.

  • Simon Ong said:

    Nice post! This will guide me even further in making web designs in the future!

    Thanks!

  • Sam said:

    I’ve been doing these ever since i began, and i get all of my friends who are starting to codelike this aswell, it just looks soo much better.

    And i agree, that little green text does give a nice warm feeling :)

  • James Smith said:

    I was advocating “STRICT” XHTML until I hit the biggest snag - file upload in AJAX enabled websites - still requires an IFRAME which isn’t allowed in XHTML strict…. unfortunately the workaround - OBJECT - doesn’t offer the same functionality as IFRAME… in this one instance.!

  • Anna said:

    What is so intuitive about tons of spacer.gif graphics (you normally see ton of those when site is designed with tables)? Learn how to layout pages with CSS, and leave tables for tabular data. Just MHO.

  • Matt said:

    The {text-transform: uppercase;} property works great for English text, but fails to transform foreign characters (such as ö -> Ö, å -> Å) for other languages.

  • Lee Bee said:

    I actually disagree with a lot of the content. You know why people use tables to layout content? Because it’s intuitive, simple and self contained. While there’s a lot of merit in code isolation (particularly for re-use and robustness), there is little reason for many people to use CSS to layout their page.

    Another reason for code going directly into files is Dreamweaver and you know what - it works and people don’t care, in fact, why should they?

    I agree with points 3 and 11 on formatting code, but as another newsflash - people were doing this before blogs were around to tell them about it. In fact in my first year studying Computer Science at uni, I got marks for code style - formatting, indenting, comments. I’m also a fan of verbose variable names - take a look at Apple’s extensive design guidelines for more examples of that.

  • mikemike said:

    Wow, nice blog - it doesn’t even encode my (x)html - let’s try this again:

    example:

    I’m a div tag

  • Kyle said:

    This was an excellent post. Well written, and very informative.

  • mikemike said:

    Very weak. Strict still validates when using tables for layout. The difference is that in Strict you cannot declare css values as attributes

    example:

    I’m a div tag

  • Chris Loft said:

    Excellent. Thank you. I make many of these mistakes - (past tense}.

  • Louise Huntley said:

    Great list, but I also disagree (somewhat) in regards to the naming conventions. “Sidebar” and “footer” have become so popular that we tend to forget that they are actually describing the style, or at least the layout more than they describe the content.

    Consider what content is going to go into those sections and name them accordingly. Try “secondary-content” or “supporting-information” or “calls-to-action” for “sidebar”, and “company-information” or “legal” for the footer.

    I’d also go so far as to say that “container”, another very popular class/id name, is also layout specific and should probably be replaced with the name of your website - div id=”www.mysite.com”.

  • Juan Pablo said:

    Great article. Thanks.

  • Derek McDonald said:

    I love clean code and whenever I develop anything I always make sure the code is readable and well commented. I find that it helps to have clean code to easily fix problems that may occur when the code is rendered.

    Great list of helpful tips there but don’t forget people that both javascript and css also need to be nice and clean too.

  • Albert said:

    Good article for Strict basic template building. Thanx

  • Davids said:

    Good Things! :D haha :)

  • Andrea said:

    Good post!
    oh, and the link “W3 MARKUP” in the footer is ugly dead..

  • I Hassen said:

    I love you guys.

  • Parker said:

    I’ve given up on the Strict DOCTYPE. I used to be its biggest advocate, but it has become less and less viable to me. The reason: user-generated content. We’re well into Web 2.0 now, whatever that means. It’s the era of interaction. I can control my code and validate it and make it semantically perfect… but the minute a user types an ampersand into a comment box, the whole thing explodes. Not to mention mismatched, unclosed, or deprecated HTML tags.

    I suppose if I got paid more I could bother to parse everything and convert characters to entities and figure out what to do with user-supplied HTML. That’s too big of a job to be feasible for me — I can’t anticipate every possible thing a user might type. With the Strict DOCTYPE, all it takes is one syntax error and the entire page fails most ungracefully. I can’t afford to let that happen on a modern dynamic site. Better to go with a Transitional DOCTYPE and let quirks mode deal with irregularities. Practicality wins out.

  • kocsmy said:

    really nice and usefull tips. thank you interweb! :)

  • Joel Heffner said:

    “Our code doesn’t use any tables for layout anyway (nice!)”
    Nice…but…tables do allow us to center blocks on the screen very easily.

  • Joe said:

    Just curious, what font are you using for the comments in your images?

  • Richard said:

    Great post!

  • Bayshore said:

    Hey my HTML always follow these principles before I read this article.

    Rage ? :D

    PS: 11 Principles *, not 12. ^^

  • deniz said:

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.