Lesson 19 of 20

HTML Best Practices

Get the Foundations Right Every Time

Most HTML problems are not exotic. They are the same handful of omissions, repeated. Before worrying about anything advanced, make sure every page you write starts from a correct foundation, because each of these lines prevents a specific, well-known failure.

<!DOCTYPE html> keeps the browser in standards mode; without it you get quirks mode, where several CSS behaviours silently change and layouts break in ways that are very hard to trace back to a missing first line. lang on the <html> element gives screen readers the right pronunciation rules. charset="UTF-8" stops regional-language text and the rupee sign turning into nonsense characters. The viewport meta tag is what makes the page usable on a phone rather than a shrunken desktop page.

Then give the page a real <title>, distinct from every other page on the site, and a <meta name="description"> written as a sentence for a human. Those two are what appear in a search result and in a shared link preview, so they are the first thing many people ever read of your work.

Example
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Annual Project Showcase — Robotics Club</title>
  <meta name="description" content="Projects built by second-year students this semester, with photos and build notes.">
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <!-- content -->
  <script src="js/main.js"></script>
</body>
</html>
  • <!DOCTYPE html> as the very first line, always
  • lang on <html>
  • <meta charset="UTF-8"> first inside the head
  • The viewport meta tag, or the page is unusable on a phone
  • A unique, descriptive <title> on every page
  • A stylesheet link in the head; scripts just before </body>

Write for the Reader You Cannot See

Accessibility is not a separate task you do at the end. Almost all of it is a consequence of choosing the right element, which costs nothing at the time and is expensive to retrofit. Every point below has appeared earlier in this course; together they cover the majority of problems found on real pages.

It helps to picture the specific people affected. Someone using a screen reader, who navigates by heading and landmark. Someone who cannot use a mouse and moves through your page with the Tab key. Someone with low vision who zooms to two hundred per cent. Someone on a slow connection with images not yet loaded. Someone who is colour blind and cannot distinguish your red error text from the black around it. None of them is an edge case, and every one of them is helped by markup you already know how to write.

The single most valuable habit is to use the element that does the job — a <button> for a button, a <label> for a label, a heading for a heading. Native elements arrive with keyboard support, focus behaviour and screen reader announcements already correct. Every time you rebuild one out of divs, you take responsibility for reproducing all of it.

  • Every image has an alt attribute — descriptive if it carries meaning, empty if it is decorative
  • Every form control has a <label>, associated by for and id or by wrapping
  • Headings step down one level at a time, and no heading is faked with CSS
  • Interactive things are <button> and <a> elements, not clickable divs
  • Link text makes sense read on its own; no "click here"
  • Colour is never the only way information is conveyed
  • Text has enough contrast against its background — roughly 4.5 to 1 for ordinary body text
  • Every iframe has a title
  • The page uses landmarks — <header>, <nav>, <main>, <footer> — and offers a skip link
Notes
  • Test with the keyboard before you call anything finished. Put the mouse down, press Tab repeatedly, and try to use the page. If you cannot reach a control, cannot see where focus is, or get stuck somewhere you cannot leave, you have found a real bug that a real person would hit.

Keep Structure, Style and Behaviour Apart

HTML describes what the content is. CSS describes how it looks. JavaScript describes what it does. Mixing them feels faster in the moment and costs you later, on every project, without exception.

In practice this means three things. Do not use HTML to control appearance — no <br> for spacing, no tables for layout, no obsolete tags such as <center> and <font>. Do not scatter style attributes through your markup; put styles in a stylesheet where they can be reused and overridden. Do not attach behaviour with onclick attributes; attach it from a script with addEventListener.

The payoff is concrete. Changing your site's colour scheme becomes one edit in one file instead of a search through every page. A designer can restyle your work without touching your markup. And when something looks wrong, you know which of the three files to open.

Example
<!-- Presentation and behaviour tangled into the markup -->
<div style="font-size: 24px; font-weight: bold; color: #7a0060;"
     onclick="openForm()">Register now</div>
<br><br>

<!-- Structure only; CSS styles it, JavaScript wires it up -->
<button type="button" class="cta">Register now</button>

/* styles.css */
.cta {
  font-size: 1.5rem;
  font-weight: 700;
  color: #7a0060;
  margin-bottom: 2rem;
}

// main.js
document.querySelector('.cta')
  .addEventListener('click', openForm);
  • No obsolete presentational tags: <center>, <font>, <big>, <marquee>
  • No <br> used for spacing, and no tables used for layout
  • Styles in a stylesheet, not in style attributes
  • Event handlers in a script file, not in onclick attributes
  • Class names that describe the content, not its appearance: error-message, not red-text

Validate, Measure, and Test Like a Visitor

You cannot review your own work by looking at it, because you know what it is supposed to do. Use tools that do not.

The W3C Markup Validation Service at validator.w3.org reads your HTML and reports unclosed tags, bad nesting, invalid attributes and duplicate ids in plain language. It takes ten seconds and it catches the exact class of bug that browsers hide by silently repairing your markup. Run it on every page before you publish.

Lighthouse, built into Chrome's Developer Tools, scores a page on performance, accessibility, best practices and SEO, and — more usefully than the score — lists specific problems with links explaining each one. Free browser extensions such as WAVE do a deeper accessibility pass. None of these tools can find everything; automated checks catch perhaps a third of accessibility problems, which is why manual testing still matters.

The manual tests are quick. Use the page with the keyboard only. Zoom the browser to two hundred per cent and check nothing is cut off or overlapping. Open it on an actual phone, not just a narrow browser window. Throttle the network in Developer Tools to a slow connection and see how long it really takes. Each of these takes a minute and each reveals something the desktop view hides.

  • Validate every page at validator.w3.org before publishing
  • Run Lighthouse in Chrome Developer Tools and read the accessibility and performance items
  • Navigate the whole page using only Tab, Shift+Tab, Enter and Space
  • Zoom to 200% and check that nothing overlaps or disappears
  • Test on a real phone, and with the network throttled to a slow connection
  • Check every link and image path after moving files, since case-sensitivity differs between your computer and the server
Notes
  • A high Lighthouse score is not the goal — a usable page is. Treat the score as a way of finding problems, not as something to optimise for its own sake.

Habits That Keep a Project Maintainable

The last group of practices has nothing to do with browsers and everything to do with the person who opens your project in six months, who will usually be you. Consistency is worth more than cleverness here: any reasonable convention followed everywhere beats a better convention followed half the time.

Two file-naming rules save a genuinely surprising amount of trouble. Use lowercase names with hyphens instead of spaces — project-notes.html, not Project Notes.html — because spaces become %20 in URLs and because most web servers are case-sensitive while your own computer is not. And name your site's main page index.html, which is the file servers look for when someone visits a folder.

Finally, keep your assets in named folders rather than in one flat pile: css/, js/, images/. A project with forty files in the root directory is hard to work in long before it is finished.

  • Indent nested elements by two spaces, consistently
  • Lowercase tag names, attribute names, class names, file names and folder names
  • Always quote attribute values with double quotes
  • Close every tag, including the optional ones
  • Comment the why, and never leave credentials or private notes in a comment
  • Organise files into css/, js/ and images/ folders
  • Name the site's main page index.html
  • Resize and compress images before uploading them, and give every one width and height
  • Use version control so you can delete old code instead of commenting it out
Ask AI