HTML
Best practices for HTML.
Table of contents
General
Define important document properties
- Doctype - Enforce standards mode and consistent rendering.
- Language - Help search engines, translation tools and speech synthesis tools.
- Character encoding - Ensure proper text rendering.
- Page title - Help humans and bots to understand what the page is about.
Good
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML best practices</title>
</head>
<body>
...
</body>
</html>
Bad
<html>
<body>
...
</body>
</html>
Put stylesheets at the top
Ensure that styles are applied as early as possible during page render by placing all stylesheet links in the <head>
section.
Good
<html>
<head>
<link rel="stylesheet" href="style.css" />
<style type="text/css"></style>
</head>
<body>
...
</body>
</html>
Bad
<html>
<head>...</head>
<body>
...
<link rel="stylesheet" href="style.css" />
<style type="text/css"></style>
</body>
</html>
Put scripts at the bottom
Prevent content being rendered from being blocked by placing all scripts just before the closing </body>
tag.
Good
<html>
<head>...</head>
<body>
...
<script type="javascript"></script>
<script type="javascript"></script>
</body>
</html>
Bad
<html>
<head>
<script type="javascript"></script>
<script type="javascript"></script>
</head>
<body>
...
</body>
</html>
Prefer specific elements to generic elements
Less markup, better readability.
Good
<body>
<header>...</header>
<main>
<article>
<section>...</section>
</article>
</main>
<footer>...</footer>
</body>
Bad
<body>
<div class="header">...</div>
<div class="main">
<div class="article">
<div class="section">...</div>
</div>
</div>
<div class="footer">...</div>
</body>
Omit value for boolean attributes
Values for boolean attributes are obsolete and should be omitted.
Good
<input type="radio" checked />
<input type="text" disabled />
Bad
<input type="radio" checked="checked" />
<input type="text" disabled="disabled" />
Images
- Define width and height - Prevent content from flickering during page load.
- Define alt attribute - Help bots and search engines to properly index images.
Good
<img src="white_horse.png" width="120" height="90" alt="White Horse" />
Bad
<img src="white_horse.png" />