20
Premium Jobs Blog Tutorials ! Courses ! Advertisement Code Series Categories ! Software & Tools ! " HTML & CSS 30 HTML Best Practices for Beginners by Jeffrey Way 14 May 2009 The most dicult aspect of running Nettuts+ is accounting for so many dierent skill levels. If we post too many advanced tutorials, our beginner audience won't benefit. The same holds true for the opposite. We do our best, but always feel free to pipe in if you feel you're being neglected. This site is for you, so speak up! With that said, today's tutorial is specifically for those who are just diving into web development. If you've one year of experience or less, hopefully some of the tips listed here will help you to become better, quicker! Without further ado, let's review thirty best practices to observe when creating your markup. 1: Always Close Your Tags Back in the day, it wasn't uncommon to see things like this: Notice how the wrapping UL/OL tag was omitted. Additionally, many chose to leave othe closing LI tags as well. By today's standards, this is # $ + & 1 2 3 <llii >Some text here. <llii >Some new text here. <llii >You get the idea. 30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b... 1 of 24 3/6/14, 10:25 AM

30 HTML Best Practices for Beginners

Embed Size (px)

DESCRIPTION

30 HTML Best Practices for Beginners - Code Tutorial from Tuts+ Web

Citation preview

Page 1: 30 HTML Best Practices for Beginners

Premium Jobs BlogTutorials ! Courses !

Advertisement

Code SeriesCategories ! Software & Tools ! "

HTML & CSS

30 HTML Best Practicesfor Beginnersby Jeffrey Way 14 May 2009

The most difficult aspect of running Nettuts+ is accounting for so manydifferent skill levels. If we post too many advanced tutorials, our beginneraudience won't benefit. The same holds true for the opposite. We do ourbest, but always feel free to pipe in if you feel you're being neglected. Thissite is for you, so speak up! With that said, today's tutorial is specificallyfor those who are just diving into web development. If you've one year ofexperience or less, hopefully some of the tips listed here will help you tobecome better, quicker!

Without further ado, let's review thirty best practices to observe whencreating your markup.

1: Always Close Your Tags

Back in the day, it wasn't uncommon to see things like this:

Notice how the wrapping UL/OL tag was omitted. Additionally, manychose to leave off the closing LI tags as well. By today's standards, this is

#

$

+

&

123

<llii>Some text here.<llii>Some new text here.<llii>You get the idea.

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

1 of 24 3/6/14, 10:25 AM

Page 2: 30 HTML Best Practices for Beginners

simply bad practice and should be 100% avoided. Always, always closeyour tags. Otherwise, you'll encounter validation and glitch issues at everyturn.

Better

2: Declare the Correct DocType

When I was younger, I participated quite a bit in CSS forums. Whenever auser had an issue, before we would look at their situation, they HAD toperform two things first:

Validate the CSS file. Fix any necessary errors.1.Add a doctype.2.

"The DOCTYPE goes before the opening html tagat the top of the page and tells the browserwhether the page contains HTML, XHTML, or amix of both, so that it can correctly interpret themarkup."

Most of us choose between four different doctypes when creating newwebsites.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">

1.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

2.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

3.

12345

<uull> <llii>Some text here. </llii> <llii>Some new text here. </llii> <llii>You get the idea. </llii></uull>

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

2 of 24 3/6/14, 10:25 AM

Page 3: 30 HTML Best Practices for Beginners

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4.

There's a big debate currently going on about the correct choice here. Atone point, it was considered to be best practice to use the XHTML Strictversion. However, after some research, it was realized that most browsersrevert back to regular HTML when interpretting it. For that reason, manyhave chosen to use HTML 4.01 Strict instead. The bottom line is that anyof these will keep you in check. Do some research and make up your ownmind.

3: Never Use Inline Styles

When you're hard at work on your markup, sometimes it can be temptingto take the easy route and sneak in a bit of styling.

Sure -- it looks harmless enough. However, this points to an error in yourcoding practices.

When creating your markup, don't even think about the stylingyet. You only begin adding styles once the page has beencompletely coded.

It's like crossing the streams in Ghostbusters. It'sjust not a good idea.-Chris Coyier (in reference to somethingcompletely unrelated.)

Instead, finish your markup, and then reference that P tag from yourexternal stylesheet.

Better

1 <pp style="color: red;">I'm going to make this text red so that it really stands out

123

#someElement > p { ccoolloorr: red;}

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

3 of 24 3/6/14, 10:25 AM

Page 4: 30 HTML Best Practices for Beginners

4: Place all External CSS Files Within the HeadTag

Technically, you can place stylesheets anywhere you like. However, theHTML specification recommends that they be placed within the documentHEAD tag. The primary benefit is that your pages will seemingly loadfaster.

While researching performance at Yahoo!, wediscovered that moving stylesheets to thedocument HEAD makes pages appear to beloading faster. This is because putting stylesheetsin the HEAD allows the page to renderprogressively.- ySlow Team

5: Consider Placing Javascript Files at theBottom

Remember -- the primary goal is to make the page load as quickly aspossible for the user. When loading a script, the browser can't continue onuntil the entire file has been loaded. Thus, the user will have to wait longerbefore noticing any progress.

If you have JS files whose only purpose is to add functionality -- forexample, after a button is clicked -- go ahead and place those files at thebottom, just before the closing body tag. This is absolutely a best practice.

Better

12345

<hheeaadd><ttiittllee>My Favorites Kinds of Corn</ttiittllee><lliinnkk rel="stylesheet" type="text/css" media="screen" href="path/to/file.css"<lliinnkk rel="stylesheet" type="text/css" media="screen" href="path/to/anotherFile.css</hheeaadd>

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

4 of 24 3/6/14, 10:25 AM

Page 5: 30 HTML Best Practices for Beginners

6: Never Use Inline Javascript. It's not 1996!

Another common practice years ago was to place JS commands directlywithin tags. This was very common with simple image galleries.Essentially, a "onclick" attribute was appended to the tag. The value wouldthen be equal to some JS procedure. Needless to say, you should never,ever do this. Instead, transfer this code to an external JS file and use"addEventListener/attachEvent" to "listen" for your desired event. Or, ifusing a framework like jQuery, just use the "click" method.

7: Validate Continuously

I recently blogged about how the idea of validation has been completelymisconstrued by those who don't completely understand its purpose. As Imention in the article, "validation should work for you, not against."

12345

<pp>And now you know my favorite kinds of corn. </pp><ssccrriipptt type="text/javascript" src="path/to/file.js"></ssccrriipptt><ssccrriipptt type="text/javascript" src="path/to/anotherFile.js"></ssccrriipptt</bbooddyy></hhttmmll>

123

$('a#moreCornInfoLink').click(ffuunnccttiioonn() { alert('Want to learn more about corn?');});

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

5 of 24 3/6/14, 10:25 AM

Page 6: 30 HTML Best Practices for Beginners

However, especially when first getting started, I highly recommend thatyou download the Web Developer Toolbar and use the "Validate HTML"and "Validate CSS" options continuously. While CSS is a somewhat easyto language to learn, it can also make you tear your hair out. As you'll find,many times, it's your shabby markup that's causing that strangewhitespace issue on the page. Validate, validate, validate.

8: Download Firebug

I can't recommend this one enough. Firebug is, without doubt, the bestplugin you'll ever use when creating websites. Not only does it provideincredible Javascript debugging, but you'll also learn how to pinpointwhich elements are inheriting that extra padding that you were unaware of.Download it!

9: Use Firebug!

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

6 of 24 3/6/14, 10:25 AM

Page 7: 30 HTML Best Practices for Beginners

From my experiences, many users only take advantage of about 20% ofFirebug's capabilities. You're truly doing yourself a disservice. Take acouple hours and scour the web for every worthy tutorial you can find onthe subject.

ResourcesOverview of FirebugDebug Javascript With Firebug - video tutorial

10: Keep Your Tag Names Lowercase

Technically, you can get away with capitalizing your tag names.

Having said that, please don't. It serves no purpose and hurts my eyes --not to mention the fact that it reminds me of Microsoft Word's htmlfunction!

Better

123

<DDIIVV><PP>Here's an interesting fact about corn. </PP></DDIIVV>

123

<ddiivv><pp>Here's an interesting fact about corn. </pp></ddiivv>

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

7 of 24 3/6/14, 10:25 AM

Page 8: 30 HTML Best Practices for Beginners

11: Use H1 - H6 Tags

Admittedly, this is something I tend to slack on. It's best practice to use allsix of these tags. If I'm honest, I usually only implement the top four; butI'm working on it! :) For semantic and SEO reasons, force yourself toreplace that P tag with an H6 when appropriate.

12: If Building a Blog, Save the H1 for the ArticleTitle

Just this morning, on Twitter, I asked our followers whether they felt it wassmartest to place the H1 tag as the logo, or to instead use it as thearticle's title. Around 80% of the returned tweets were in favor of the lattermethod.

As with anything, determine what's best for your own website. However, ifbuilding a blog, I'd recommend that you save your H1 tags for your articletitle. For SEO purposes, this is a better practice - in my opinion.

13: Download ySlow

12

<hh11>This is a really important corn fact! </hh11><hh66>Small, but still significant corn fact goes here. </hh66>

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

8 of 24 3/6/14, 10:25 AM

Page 9: 30 HTML Best Practices for Beginners

Especially in the last few years, the Yahoo team has been doing somereally great work in our field. Not too long ago, they released an extensionfor Firebug called ySlow. When activated, it will analyze the given websiteand return a "report card" of sorts which details the areas where your siteneeds improvement. It can be a bit harsh, but it's all for the greater good. Ihighly recommend it.

14: Wrap Navigation with an Unordered List

Each and every website has a navigation section of some sort. While youcan definitely get away with formatting it like so:

I'd encourage you not to use this method, for semantic reasons. Your jobis to write the best possible code that you're capable of.

Why would we style a list of navigation links withanything other than an unordered LIST?

The UL tag is meant to contain a list of items.

12345

<ddiivv id="nav"> <aa href="#">Home </aa> <aa href="#">About </aa> <aa href="#">Contact </aa></ddiivv>

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

9 of 24 3/6/14, 10:25 AM

Page 10: 30 HTML Best Practices for Beginners

Better

15: Learn How to Target IE

You'll undoubtedly find yourself screaming at IE during some point oranother. It's actually become a bonding experience for the community.When I read on Twitter how one of my buddies is battling the forces of IE, Ijust smile and think, "I know how you feel, pal."

The first step, once you've completed your primary CSS file, is to create aunique "ie.css" file. You can then reference it only for IE by using thefollowing code.

This code says, "If the user's browser is Internet Explorer 6 or lower,import this stylesheet. Otherwise, do nothing." If you need to compensatefor IE7 as well, simply replace "lt" with "lte" (less than or equal to).

16: Choose a Great Code Editor

Whether you're on Windows or a Mac, there are plenty of fantastic codeeditors that will work wonderfully for you. Personally, I have a Mac and PCside-by-side that I use throughout my day. As a result, I've developed a

12345

<uull id="nav"> <llii><aa href="#">Home</aa></llii> <llii><aa href="#">About</aa></llii> <llii><aa href="#">Contact</aa></llii></uull>

123

<!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="screen" href="path/to/ie.css" /><![endif]-->

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

10 of 24 3/6/14, 10:25 AM

Page 11: 30 HTML Best Practices for Beginners

pretty good knowledge of what's available. Here are my topchoices/recommendations in order:

Mac LoversCodaEspressoTextMateAptanaDreamWeaver CS4

PC LoversInTypeE-Text EditorNotepad++AptanaDreamweaver CS4

17: Once the Website is Complete, Compress!

By zipping your CSS and Javascript files, you can reduce the size of eachfile by a substantial 25% or so. Please don't bother doing this while still indevelopment. However, once the site is, more-or-less, complete, utilize afew online compression programs to save yourself some bandwidth.

Javascript Compression ServicesJavascript CompressorJS Compressor

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

11 of 24 3/6/14, 10:25 AM

Page 12: 30 HTML Best Practices for Beginners

CSS Compression ServicesCSS OptimiserCSS CompressorClean CSS

18: Cut, Cut, Cut

Looking back on my first website, I must have had a SEVERE case ofdivitis. Your natural instinct is to safely wrap each paragraph with adiv, and then wrap it with one more div for good measure. As you'llquickly learn, this is highly inefficient.

Once you've completed your markup, go over ittwo more times and find ways to reduce thenumber of elements on the page. Does that ULreally need its own wrapping div? I think not.

Just as the key to writing is to "cut, cut, cut," the same holds true for yourmarkup.

19: All Images Require "Alt" Attributes

It's easy to ignore the necessity for alt attributes within image tags.Nevertheless, it's very important, for accessibility and validation reasons,that you take an extra moment to fill these sections in.

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

12 of 24 3/6/14, 10:25 AM

Page 13: 30 HTML Best Practices for Beginners

Bad

Better

20: Stay up Late

I highly doubt that I'm the only one who, at one point while learning,looked up and realized that I was in a pitch-dark room well into the early,early morning. If you've found yourself in a similar situation, rest assuredthat you've chosen the right field.

The amazing "AHHA" moments, at least for me, always occur late at night.This was the case when I first began to understand exactly whatJavascript closures were. It's a great feeling that you need to experience, ifyou haven't already.

21: View Source

What better way to learn HTML than to copy your heroes? Initially, we'reall copiers! Then slowly, you begin to develop your own styles/methods.So visit the websites of those you respect. How did they code this andthat section? Learn and copy from them. We all did it, and you should too.(Don't steal the design; just learn from the coding style.)

1 <IIMMGG SRC="cornImage.jpg" />

1 <iimmgg src="cornImage.jpg" alt="A corn field I visited." />

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

13 of 24 3/6/14, 10:25 AM

Page 14: 30 HTML Best Practices for Beginners

Notice any cool Javascript effects that you'd like to learn? It's likely thathe's using a plugin to accomplish the effect. View the source and searchthe HEAD tag for the name of the script. Then Google it and implement itinto your own site! Yay.

22: Style ALL Elements

This best practice is especially true when designing for clients. Justbecause you haven't use a blockquote doesn't mean that the client won't.Never use ordered lists? That doesn't mean he won't! Do yourself aservice and create a special page specifically to show off the styling ofevery element: ul, ol, p, h1-h6, blockquotes, etc.

23: Use Twitter

Lately, I can't turn on the TV without hearing a reference to Twitter; it'sreally become rather obnoxious. I don't have a desire to listen to LarryKing advertise his Twitter account - which we all know he doesn'tmanually update. Yay for assistants! Also, how many moms signed up foraccounts after Oprah's approval? We can only long for the day when itwas just a few of us who were aware of the service and its "watercooler" potential.

Initially, the idea behind Twitter was to post "what you were doing."Though this still holds true to a small extent, it's become much more of anetworking tool in our industry. If a web dev writer that I admire posts a

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

14 of 24 3/6/14, 10:25 AM

Page 15: 30 HTML Best Practices for Beginners

link to an article he found interesting, you better believe that I'm going tocheck it out as well - and you should too! This is the reason why sites likeDigg are quickly becoming more and more nervous.

If you just signed up, don't forget to follow us: NETTUTS.

24: Learn Photoshop

A recent commenter on Nettuts+ attacked us for posting a fewrecommendations from Psdtuts+. He argued that Photoshop tutorials haveno business on a web development blog. I'm not sure about him, butPhotoshop is open pretty much 24/7 on my computer.

In fact, Photoshop may very well become the more important tool youhave. Once you've learned HTML and CSS, I would personallyrecommend that you then learn as many Photoshop techniques as

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

15 of 24 3/6/14, 10:25 AM

Page 16: 30 HTML Best Practices for Beginners

possible.

Visit the Videos section at Psdtuts+1.Fork over $25 to sign up for a one-month membership to Lynda.com.Watch every video you can find.

2.

Enjoy the "You Suck at Photoshop" series.3.Take a few hours to memorize as many PS keyboard shortcuts as youcan.

4.

25: Learn Each HTML Tag

There are literally dozens of HTML tags that you won't come across everyday. Nevertheless, that doesn't mean you shouldn't learn them! Are youfamiliar with the "abbr" tag? What about "cite"? These two alone deservea spot in your tool-chest. Learn all of them!

By the way, in case you're unfamiliar with the two listed above:

abbr does pretty much what you'd expect. It refers to anabbreviation. "Blvd" could be wrapped in a <abbr> tag because it'san abbreviation for "boulevard".cite is used to reference the title of some work. For example, if youreference this article on your own blog, you could put "30 HTML BestPractices for Beginners" within a <cite> tag. Note that it shouldn't beused to reference the author of a quote. This is a commonmisconception.

26: Participate in the Community

Just as sites like ours contributes greatly to further a web developer'sknowledge, you should too! Finally figured out how to float your elementscorrectly? Make a blog posting to teach others how. There will always bethose with less experience than you. Not only will you be contributing tothe community, but you'll also teach yourself. Ever notice how you don'ttruly understand something until you're forced to teach it?

27: Use a CSS Reset

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

16 of 24 3/6/14, 10:25 AM

Page 17: 30 HTML Best Practices for Beginners

This is another area that's been debated to death. CSS resets: to use ornot to use; that is the question. If I were to offer my own personal advice,I'd 100% recommend that you create your own reset file. Begin bydownloading a popular one, like Eric Meyer's, and then slowly, as youlearn more, begin to modify it into your own. If you don't do this, you won'ttruly understand why your list items are receiving that extra bit of paddingwhen you didn't specify it anywhere in your CSS file. Save yourself theanger and reset everything! This one should get you started.

28: Line 'em Up!

0102030405060708091011121314151617181920212223242526272829303132333435

html, body, div, span, h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,img, ins, kbd, q, s, samp,small, strike, strong, dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td { mmaarrggiinn: 0; ppaaddddiinngg: 0; bboorrddeerr: 0; oouuttlliinnee: 0; ffoonntt--ssiizzee: 100%; vveerrttiiccaall--aalliiggnn: baseline; bbaacckkggrroouunndd: transparent;}body { lliinnee--hheeiigghhtt: 1;}ol, ul { lliisstt--ssttyyllee: none;}blockquote, q { qquuootteess: none;}blockquote:before, blockquote:after,q:before, q:after { ccoonntteenntt: ''; ccoonntteenntt: none;} table { bboorrddeerr--ccoollllaappssee: collapse; bboorrddeerr--ssppaacciinngg: 0;}

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

17 of 24 3/6/14, 10:25 AM

Page 18: 30 HTML Best Practices for Beginners

Generally speaking, you should strive to line up your elements as best aspossible. Take a look at you favorite designs. Did you notice how eachheading, icon, paragraph, and logo lines up with something else on thepage? Not doing this is one of the biggest signs of a beginner. Think of itthis way: If I ask why you placed an element in that spot, you should beable to give me an exact reason.

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

18 of 24 3/6/14, 10:25 AM

Page 19: 30 HTML Best Practices for Beginners

Advertisement

29: Slice a PSD

Okay, so you've gained a solid grasp of HTML, CSS, and Photoshop. Thenext step is to convert your first PSD into a working website. Don't worry;

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

19 of 24 3/6/14, 10:25 AM

Page 20: 30 HTML Best Practices for Beginners

it's not as tough as you might think. I can't think of a better way to putyour skills to the test. If you need assistance, review these in depth videotutorials that show you exactly how to get the job done.

Slice and Dice that PSDFrom PSD to HTML/CSS

30: Don't Use a Framework...Yet

Frameworks, whether they be for Javascript or CSS are fantastic; butplease don't use them when first getting started. Though it could beargued that jQuery and Javascript can be learned simultaneously, thesame can't be made for CSS. I've personally promoted the 960 CSSFramework, and use it often. Having said that, if you're still in the processof learning CSS -- meaning the first year -- you'll only make yourself moreconfused if you use one.

CSS frameworks are for experienced developers who want to savethemselves a bit of time. They're not for beginners.

Follow us on Twitter, or subscribe to theNETTUTS RSS Feed for more daily webdevelopment tuts and articles.

30 HTML Best Practices for Beginners - Tuts+ Code Tutorial http://code.tutsplus.com/tutorials/30-html-best-practices-for-b...

20 of 24 3/6/14, 10:25 AM