Top 10 best practices for front-end web developers

by Jean. 99 Comments -

Front-end web developent can seem to be easy at first, but producing a clean, semantic, and cross-browser code is definitely a hard job. In this article, I have compiled the top 10 best practices that have been useful to me in the past 3 years.

Explain which div you’re closing

Most of the time when I’m viewing a website source, I see, at the very bottom of the page, an almost endless list of closing </div> tags. In fact, many beginners think they just have to use divs instead of tables to produce quality code. Divs are cleaners than tables, but without proper code organization, it can be as (or even sometimes more) messy as table based code.

Using indentation is a good start. But a tip that can definitely make you save lot of time is to comment every div tag you’re closing, as shown in the example below:

<div id="header">
  <div id="sub" class="first left">
    ...
  </div><!-- #sub.first.left -->
</div><!-- #header -->

Use a CSS reset

Unless you’re a beginner or if you were on vacation on a desert island for the last 6 years, you might already know how useful a CSS reset it. Because by default, browsers don’t apply the same default styling to HTML elements, a CSS reset will ensure that all element have no particular style so you can define your own without the risk of many cross-browser rendering issues.

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}
del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

Source: http://meyerweb.com/eric/tools/css/reset/index.html

Don’t use @import

CSS files can be included using the @import directive. This can be useful when, for example, you want to include a stylesheet into another. Another common practice is to include CSS file in html documents using the following:

<style type="text/css>
  @import url('a.css');
  @import url('b.css');
</style>

While it works, the @import directive is much slower than the other way to include stylesheets into a html document:

<link rel='stylesheet' type='text/css' href='a.css'>
<link rel='stylesheet' type='text/css' href='proxy.css'>

It will not make a difference on low traffic websites, but if you have the chance to own a popular website, don’t waste your visitor’s time using @import.
Source: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

“Smush” your images

Being a developer, I always found that optimizing my images for the web wasn’t easy. I tried the good old “Save for web” Photoshop command, but most of the time, I ended up with images that were either too big or without a sufficient quality.
As a result, I had the bad habit of using unoptimized images on my websites. This isn’t a problem when you don’t have to care about your site’s bandwidth, but after my recent switch on my vps.net virtual private server, I had to be careful with image sizes.

At this time, I found a very cool tool named Smush It: You enter your unoptimized image url, and Smush It will create a perfectly optimized image for you. You can save up to 70% of the file size, while keeping the original quality. As an example, all the images from my list of online code editors have been “smushed”.

Don’t mix CSS with HTML

As a markup language, the right use of HTML is to organize documents by defining a header, a footer, lists, blockquotes, etc. Some time ago, front-end web developers often used now deprecated HTML attributes to style a particular element.
Nowadays, the style attribute allows developers to insert CSS directly into a html document. This is very useful for testing or when you’re in a hurry. But the style attribute is bad practice, that goes completely against the CSS philosophy.

The following example illustrates how dirty and hard to read a simple line of code can become, with the style attribute:

<a href="http://www.catswhocode.com" style="background:#069;padding:3px;font-weight:bold;color:#fff;">Cats Who Code</a>

Don’t mix Javascript with HTML

Just like mixing your html code with css is bad practice, you shouldn’t use any Javascript in your html documents. The following bad practice illustrates an onclick event:

<a id="cwc" href="http://www.catswhocode.com" onclick="alert('I love this site!');">Cats Who Code</a>

The same result can be achieved using unobstructed Javascript. In this example, I’m using the popular jQuery framework:

$(document).ready(function() {
  $('#cwc').click(function() {
    alert('I love this website');
  });
});

This may seems a bit harder at first, especially for beginners; but it is definitely not, and it will keep your html document clean.

Use conditional comments

You know it, IE sucks, and some clients suck even more by requiring you to create webpages which are compatible with this obsolete browser. To target specific versions of IE, you can use the well known IE hacks, as shown below:

height: 200px; /* normal browsers */
_height: 300px; /* IE6 */
.height: 250px; /* IE7 */
*height: 350px; /* All IEs */

Those hacks are extremely useful sometimes, but they are not the best way to target a specific version of IE, and it will cause your CSS validation to fail.

Instead, you should use the conditional comment shown below to target IE6.

<link href="style.css" rel="stylesheet" type="text/css" />

<!--[if lte IE 6]>
  <link href="ie.css" rel="stylesheet" type="text/css" />
<![endif]-->

Place Javascript file at the bottom

A popular practice of the late 90′s/early 2000′s was to place Javascript files within the <head> and </head> tags. The problem is that your javascript files will be loaded first, and consequently your content will be loaded after.

By placing Javascript files at the bottom of your documents, you’ll ensure that JS files will be loaded only when the content has been properly displayed.

    ...
    <script type='text/javascript' src='jquery.js?ver=1.3.2'></script>
  </body>
</html>

Use HTML semantically

HTML is not a programming language. It is a markup language, used to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, and more.
If you started to create websites in the good old 90′s or in the beginning of the century, you know how dirty the markup was at the time. But happilly, it has evolved.
Among other things, it is important to use html element semantically. As an example, a navigation menu should always be an unordered list:

<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">Blog</a></li>
</ul>

Test WHILE you build to avoid cross-browser issues

One of the biggest mistake I ever made when developing html, CSS, and javascript, was not to test my pages on multiple browser while I was writing them. Instead, I used to write all my code and just view in Firefox to see how it was rendered.
In theory, this should be good. But as you know, cross-browser issues are a major problem for front-end developers, especially due to IE. If you test your documents on Firefox/IE/Chrome while your writing it, cross-browser rendering problems will be much easier to fix. I have lost hours not doing it, so I hope this final tip will help you saving your precious time. To test on multiple versions of IE, I use this very handy tool. Happy coding ;)

Comments (99) - Leave yours

  1. Alan said:

    Great post for beginners, and i even picked up a couple of things too. I had thought about putting my javascript at the bottom of the page, but never actually done it, i think from now on i will do that, if it increases load speeds.

  2. paul said:

    there’s an interesting article that discusses an alternative aproach to css resests:
    http://carsonified.com/blog/design/setting-rather-than-resetting-default-styling/

  3. RussellUresti said:

    Very good rules to follow. I think commenting the div you’re closing may be a bit of overkill, though. Good code formatting should make it clear where a block of code starts and ends. But if you’re opening a in one file and closing it in another, then I can see how commenting would be needed.

    I think a few that could be added in would be these:

    1. Use sprites to reduce sever lookups for images.
    2. Minify all CSS and JS before publishing.
    3. Don’t use JS to modify styles (like using the .css() function in jQuery), but rather append class names that have those styles attached.

    • Shane Bailey said:

      There are some bugs, in IE of course, when loading your javascript in the body. The only way I know of getting around them is to load the script in the header.

  4. M.R. said:

    Thanks for posting. Nice article. Though I had read about CSS reset I had never done it, maybe I should start doing it.

    • jason said:

      I have a style sheet called reset.css – and I @import it at the beginning of my style.css – so my base reset styles I use on all sites is always separate from the specific styles used for the site. It’s certainly permissible, and preferred by some, to put the reset styles at the top of their base stylesheet. They could both be linked separately in the head of the document, but I prefer the @import method, it seems a lot cleaner to me, and like most of you here, I feel like code should be as pretty as the site itself.

      • Oriol Torras said:

        There are performance issues using @import vs link css inclusion, you should read Steve Souders article: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

  5. Marta said:

    Great tips!

    Other way to avoid using hacks is giving a class with the operational system and browser. Some php or jQuery scripts can do that. So you can use almost the same way of the hacks, in the same CSS file, but validating. :)

  6. Jorge Pedret said:

    I would recommend everybody his last point “Test WHILE you build to avoid cross-browser issues”! I’ve been doing it for a while now, and, seriously, I don’t hate IE as much any more (I can’t believe I just said that)… If you fix it while you’re coding, you notice how easy is to fix an specific error, instead of fixing all the mess at the end, when you have a bunch of accumulated errors, don’t know what bug is what and it looks horrible not-even-close-to-what-its-supposed-to-look-like.

    Great article!

  7. Nick Burd said:

    This was a GREAT post!
    Most are already things that are pretty much absolute.. But I particularly like the first one, about marking the div’s you are closing.

    Thank you very much.

  8. Jen said:

    Very nice, this is an excellent resource for students and those without a lot of experience yet. Shoot – I know a few experienced pros who could use these reminders. :)

  9. jason said:

    I use @import to stick my reset stylesheet into my site stylesheet. I like it that way, and I think I’m going to keep using it (sorry).

    I think it’s essential, and certainly a best practice, that front end developers use includes, wether PHP or .net – I think the concept of DRY (don’t repeat yourself) is certainly applicable to front end development. Is there honestly such thing as someone who only does javascript/(x)HTML/CSS anymore. Knowing a little, miniscule amount of back end programming saves hours in the long run.

  10. Matt said:

    All those practices are great and should be used by all designers. My favourite is “test while you build”. It can save you a lot of headaches later.

  11. Daniel said:

    2 more tools to speed up your sites loading time:

    http://www.sitepoint.com/dustmeselectors/ is a great tool to find unused selectors in your css files and http://csstidy.sourceforge.net/ is a command line tool to minimize your .css files – it removes all the comments, white space etc. and shortens color, padding and margin declarations: #FFFFFF => #fff, margin:0px 5px 0px 5px => margin:0 5px
    quite handy, but be careful since it might also remove css hacks for ie or “invalid” css code.

  12. Pali Madra said:

    Great posts.

    Some of them my team and I do not follow and we should start following.

    Do you think there are any bugs that IE6 and IE7 have which need to be taken care of. Lots of customers complain about something or the other when they test the websites on IE6 or IE7 which is default browser for them.

    Thanks

  13. Robert said:

    I agree that commenting the end of every div might be a bit overkill. It’s important to format you code in a way that can be read easily, and use comments when it could be unclear.

    Wow…I’ve ALWAYS put my javascript in the head. I think I’ll try putting it below and see what happens. Oh, and thanks for the smush link. I think I’m going to start using that.

  14. Kai Chan Vong said:

    Surely the conditional comments would be in this order?

    height: 200px; /* normal browsers */
    *height: 350px; /* All IEs */
    _height: 300px; /* IE6 */
    .height: 250px; /* IE7 */

    Otherwise we’ll just be overwriting our specifics with the star hack.

  15. Anton Samper said:

    As a web dev, I already use a lot of these techniques but I also think that commenting the closng divs is overkill, however a good work around and something that we should all be doing is indenting the code properly, whether its with tabs or spaces, that should get around readability issues

    • Alastair Hodgson said:

      I think it depends Anton, I use good indentation always, and comments at the end of divs where I can’t easily see the start of the div. It’s especially useful if your code is split into separate template files. but if you just have a little div block where you can easily see the start and finish of the tag, then you don’t really need an end comment, use at your discretion.

  16. Federica Sibella said:

    Thanks for sharing, very helpful tips.
    Especially the Smush.it site for optimizing images is really useful.
    As for js in the head or at the end: I would say that it depends on the role of your script, in my experience some work smoother if loaded first (for example those adjusting the content on the basis of the screen size).

    • Jean-Baptiste Jung said:

      No, the first tip don’t suck at all. Ok, the document may take some millisecond more to load, but have you ever edited a file directly on a server, using a old version of Vi and a 1024*768 px resolution?
      I did, and believe me, a file properly indented in an advanced text editor such as Textmate can look completely different if edited directly on the server.
      This is why I recommend using comments to show which div you’re closing.

      • Jorgen said:

        Use spaces not tabs to indent. This makes sure your document is always properly displayed in any type of editor and web CSV as well. Using comments for every tag you’re opening or closing not only adds extra page weight but also clutters your code making it unreadable.

        Also using a reset is debatable, why would one remove the default styling and then restyle the element?

        • Hua Tuo said:

          Not only does commenting make your HTML more comprehensible –
          especially commenting the closing divs — but it does not add any page
          weight at all in a proper CMS that does not transmit the comments
          to the user’s browser.

        • Jason said:

          I subscribe and employ every one of these tips, except for one. I still load javascript in the head, but use (document).ready to postpone it.

          Commenting your code makes sense, no matter what type of language you’re using. In any event, if you’re worried about a few extra characters of commenting, shouldn’t you be taking care of that by compressing the whole file anyway?

      • Moses Adrien said:

        @Jean-Baptiste I can really agree with you on the commenting tip. I tend to have to edit files in VI editor so much and its so annoying when I have to work with code thats badly indented and not commented. Wastes alot of time :(

    • Ashfame said:

      You weigh things on you own and then decide.

      If you are looking for performance gain on an edge like 99-100, then leave out comments on the cost of some commenting which can actually help you when you need to make a change directly on server like Jean said.

  17. Russell Bishop said:

    Good few tips for people starting out, especially with keeping HTML semantic, which I feel is easy to forget when you’re starting out. For example, writing “” seems more logical than “”

    Cheers CatsWhoCode!

  18. Tyson Cadenhead said:

    Most of these are really good points. If you’re using a JavaScript library like jQuery or Ext, there are listeners that don’t activate until the page is loaded, which I think is a better practice than putting the scripts at the end of the body tag. Even with plain JavaScript, you can call a window.onload function that contains all of the JavaScript. Having JavaScript at the bottom the code is just messy and not needed.

  19. Dave said:

    Great article! I dont use css resets and I am going to start using them. I also did not know that the @import had a slower load time. Thanks for the info. =)

  20. Tom said:

    I use inline styles for html emails. Mail Chimp and other email broadcasting services rip out your header including all your CSS. So this is one example of where inline styles are needed.

  21. Steven Rossi said:

    Wonderful list. Besides sprites, this is exactly the top 10 things I would list.

    Sidenote: I like the “Subscribe without commenting” feature. I may have to steal that idea!

  22. Lucian Apostol said:

    It seems i have so much to learn about CSS. I don’t create design from scratch, o only edit existing ones and i don’t pay too much attention on this stuff, but maybe one day i will need them.

  23. Janet Wagner said:

    Hello. I’ve been reading your blog for quite a while now and really like it. Most of this list is great advice, but I’m afraid I have to disagree with your advice regarding placement of Javascript and the use of a CSS reset. Where the Javascript is placed on a web page actually depends on how the script functions. Some scripts may not work if they are placed in the bottom (ref: http://www.w3schools.com/js/js_whereto.asp). And for the CSS reset, I think that is more of a personal preference than a best practice. Some programmers use CSS reset and some don’t. (ref: http://snook.ca/archives/html_and_css/no_css_reset/). Again, I really like your blog, please keep up the great work!

  24. TheAL said:

    I am really good at commenting code when it’s not markup. I’ll comment the heck out of Perl and C++. I’ve always been told that I over-comment VB (no idea why, probably because it’s the first programming I learned back in the 90′s). I’m iffy when it comes to PHP, but I still comment enough. I comment CSS nowadays, but I had to force the habit. I don’t comment HTML for squat. I use a text editor that really works well with indenting to let me know which tag(s) I am in and which ending tag goes with what. But indenting is key for this editor to work like this. If anyone else inherited my HTML they would hate me. *lmao* Anyway, I can’t say I disagree with anything here. The “javascript on bottom” issue is pretty debatable, though. Even W3C still says funciton-specific scripts should be in the head, along with calling external scripts, and that everything else should be at bottom or, if absolutely necessary, in-body where it writes content.

  25. Bilal Aslam said:

    Excellent tips! I love “Explain which div you’re closing” & “Place Javascript file at the bottom”. They really make a developer’s life much more easier!

  26. Brian said:

    Commenting Div closes is a brilliant idea, and not something I have thought of doing and I spend so many hours looking through code to work out which div has been closed and which pairs belong together.

  27. Brad Proctor said:

    Great list of tips. The only thing that I don’t do from this list is put my menus in an unordered list. I used to but it just seemed like extra code for no purpose. Just use a tags, set them to display:block. No need for the list. Want them horizontal? use float:left

    I should probably be commenting my ending divs, but I rarely do.

  28. david said:

    Hello. I’ve been reading your blog for quite a while now and really like it. Most of this list is great advice, but I’m afraid I have to disagree with your advice regarding placement of Javascript and the use of a CSS reset. Where the Javascript is placed on a web page actually depends on how the script functions.

  29. Lisa said:

    Thanks, I will have good use for this. Regarding which browser is the best I agree with some of the commenters that IE still is the best one, even though Firefox have put up a good fight.

  30. Ahmad Alfy said:

    Thanks for sharing the tips
    I really like the first one, I always work with others’ code and these comments on closing tags helps me working faster. I am gonna use it too in the future
    Regards

  31. Muhammad Ghazali said:

    Hei dude! This is very useful post for me, really good practices that I should follow, especially the section that describe about placing the Javascript file at the bottom. You done a great job! Thank you :)

  32. Jeff Dickey said:

    SmushIt is now embedded within YSlow, and thus is accessible only from Firefox (Opera and Safari users appear to be SOL). However, experimenting on a couple of smallish images implies that most of the compression is due to the stripping out of EXIF and other such metadata. If metadata is important to you – for instance, if you have a copyright notice embedded in the EXIF data – then this is obviously something that won’t be so attractive to you, anyway.

    If you’re serving enough image data that bandwidth usage is a real concern, try caching via a CDN.

  33. fritz said:

    Good list for beginners, excpet the ‘Explain which div you’re closing’ which not only is an overkill, but it gives you more work to do – you have to keep updating those comments manually as you change the code, otherwise they’ll be worthless.

    I prefer using editors that allow to collapse tags

  34. Lex said:

    This is a great post. A couple of these were “duh, why didn’t I think of this” – esp. Javascript at the bottom. Awesome! I didn’t know about smush, will check it out – although I’ve always had good results with photoshop “save for web”, using .gif if it’s an image with a low number of colors, or .jpg if a high number ,and setting the compression to 60 or 80%.

    I have to say though, I’m (secretly of course) in favor of the conspiratorial practice of designing pages that fail in IE. If everyone did this, more people would give up on IE…. mwahahaaa ;)

  35. McGonagall said:

    If you are using JavaScript jQuery or extension, such as libraries have an audience, cannot activate page loading before, I think this is a better than the script, actually the tag

  36. Carpool said:

    I’ll add one: Excessively nest your divs! Always use a structure with a few more ‘s as well. With a proper reset, div’s are completely transparent without classes, and using multiple ones ALWAYS comes in handy when tweaking your CSS for compliance (in IE). Eg: placing padding on .inner, while placing width on .outer… I recommend it.

  37. Niko said:

    To reset a css you can write it like this. I think it s the better and shorter way. The Star-selector selects all tags without coding them all hard in your CSS-file.

    *{
    margin:0;
    padding:0;
    ….
    }

  38. Doug Avery said:

    Thanks for writing this! A year ago, I would’ve agreed with you on all of it, but I’ve made a few observations since:

    After a long time spent writing close comments at the end of divs, I decided NO MORE. If you’re using a decent editor and lining your code up right, you should already have visual indicators and folding at these points — adding this comments just creates more code for users to download and (often) for FEDs to mess up later. In my experience, these just add to the document overhead

    As for smushit, I’d suggest mac users try the new ImageOptim instead ( http://imageoptim.pornel.net/ ), a lightning-fast optimizer that can squish down whole folders of images in a few seconds.

    Finally, I think it’s possible that the age of conditional CSS hacks and separate stylesheets has passed — CSS hacks are hard to read and, on principle, working on shaky ground, while separate files are, IMHO, kind of a pain to maintain alongside your regular CSS. I’d suggest FEDs look into Paul Irish’s body tag method:

    http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/

    With this method, you can write rock-solid css that’s easier to maintain and read:

    .comment {
    float: left;
    margin: 0 0 0 40px;
    }

    .ie6 .comment {
    margin-left: 20px;
    }

    Have you guys played with any of these methods? Great post, thanks for putting this together!

  39. Cara said:

    Thanks for this info. I had to laugh at “if you were on vacation on a desert island for the last 6 years” because in a way, that’s me (minus the vacation part). I was a developer from late 1994-2005 but for the last 6 years, I’ve been working in visual effects for movies. Now I want to get back into Web Development and am trying to catch up with 6 years of info. Thanks for the help!

  40. Vik said:

    Thanks for sharing this article, which has some nice tips!

    One ‘sub-tip’ that may be dated, though, is that under the last heading (“Test WHILE you build to avoid cross-browser issues”), the link near the end (“this very handy tool”) goes to a page called Browsers on Spoon (http://spoon.net/Browsers/), which may no longer support IE. Here’s what it says at the top of the page under the Microsoft Internet Explorer heading:

    “Come back soon for more information on how to use Internet Explorer on Spoon.net!”

    That’d be really interesting if they did support multiple versions of IE; did they use to actually do this? I can imagine that they might’ve withdrawn support for IE because of some kind of technical issues related to have several versions open at once.

    For my own work, I’m often using some kind of VM like VMWare or Parallels. Any more info on what’s up with Spoon.net would be appreciated, Thanks!

  41. Ben Arellano said:

    Great post! I love the “comment” suggestion on divs. Too many developers today don’t take the time for commenting code. They are ignorant to the fact that someone else in the future might perhaps update or upgrade that code. I call it coders etiquette…

  42. carl-michael hughes said:

    thanks for the article. I wanted to add what I recently learned: that having the designers make sprites work horizontally can actually improve load times. whaaaa? cool.

  43. Dave said:

    I just like the helpful information you provide to your articles.
    I’ll bookmark your weblog and take a look at again right here frequently. I’m fairly sure I will be informed many new
    stuff right right here! Good luck for the following!

  44. Troy Thibodeaux said:

    So if your JS is at the bottom, can’t the opposite problem happen where the content loads before the functionality is enabled? Like an event that fires off a modal popup or something. Could it not happen where the button doesn’t work for a split second? I personally work on a lot of small sites and putting JS in the head has never been an issue, but I am currently working on dashboard with tons of calls to frameworks, plugins, databases, etc., so moving my scripts to the bottom might make a difference.

  45. Troy Thibodeaux said:

    I guess the real answer as to where to put JS (head or body) might be that it depends.

    Facebook (head and body)
    Amazon (head and body)
    CNN (head and body)
    www.catswhocode.com (head and body)

    Great post!

  46. Bartdude said:

    As a side note, I would like to add that semantically speaking, I will always represent an navigation as a OL tag, not a UL. Although some might say the order is not as important as in a step by step procedure or so, you would find it strange to get the “home” link in between other navigation items for example, as other combinations might sometimes seem strange depending on the site. For example on a product site, you may want your navigation to answer your prospects questions in a certain order : What does the product do ?, who are those guys ? how much does it cost ? how can I get it?

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!