HTML Formatting and Semantic Markup Explained
Learn HTML formatting conventions and semantic elements like nav, main and article, so your markup is readable, accessible and search-friendly.
%20(1).jpg)
HTML is the first language most developers learn and the one they revisit least. It is forgiving, so pages "work" even when the markup is messy. But messy markup has a cost: it is harder to read, harder to maintain, worse for accessibility and weaker for search engines. This guide covers two linked skills. First, how to format HTML so people can read it. Second, how to write semantic markup so browsers, screen readers and search engines understand it. You will learn the conventions, the elements that matter, the common mistakes and how to automate the routine parts.
What is HTML formatting, and what is semantic markup?
HTML, HyperText Markup Language, defines the structure of web pages. Its living specification is maintained by the WHATWG, and practical documentation lives in the MDN HTML reference.
The two ideas in this article are easy to confuse, so keep them apart:
- Formatting is layout: indentation, line breaks, attribute order and quoting. It affects how readable the source is to humans. It has almost no effect on how the page renders.
- Semantics is meaning: choosing
<nav>for navigation and<button>for a button instead of a<div>for everything. It affects accessibility, SEO, default behaviour and maintainability.
Compare these two snippets. Both look similar in a browser once styled, but only one describes what its parts are:
<div class="top">
<div class="menu"><div class="item">Home</div><div class="item">Blog</div></div>
</div>
<header>
<nav aria-label="Main">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog">Blog</a></li>
</ul>
</nav>
</header>
The second version gives assistive technology a landmark to jump to, gives crawlers a clear structure, and gives developers meaningful names.
Core formatting conventions
Teams vary on details, but these habits are widely shared.
Indent nested elements. Use two spaces (or four, or tabs) consistently. Each child sits one level deeper than its parent.
One block-level element per line. Put <section>, <p>, <ul> and similar on their own lines so structure is visible.
Lowercase tags and attributes. HTML is case-insensitive, but lowercase is the universal convention.
Quote attribute values. Write class="card", with double quotes. Unquoted values work in simple cases and fail with spaces or special characters.
Declare the doctype and language. Start with <!DOCTYPE html> and set <html lang="en">. The language attribute helps screen readers pronounce text correctly.
Close what you open. Some elements, such as <p> and <li>, may omit closing tags under the specification, but explicit closing tags make the structure obvious and avoid surprises.
Wrap long attribute lists. When a tag has many attributes, put one per line:
<img
src="/images/hero.jpg"
alt="A developer reviewing formatted code on a laptop"
width="1200"
height="630"
loading="lazy"
/>
Mind inline whitespace. Whitespace between inline elements is meaningful: a space or line break between two <a> tags renders as a visible gap. Be careful when a formatter reflows inline content. The MDN page on whitespace in the DOM explains the rules.
The semantic elements that matter most
HTML5 introduced a set of elements that describe page regions. Use them in place of generic containers wherever they fit.
| Element | Use it for |
|---|---|
<header> |
Introductory content for a page or section |
<nav> |
A block of navigation links |
<main> |
The unique, primary content (one per page) |
<article> |
A self-contained piece, such as a post or comment |
<section> |
A thematic group of content, usually with a heading |
<aside> |
Tangential content such as a sidebar |
<footer> |
Footer information for a page or section |
<figure> / <figcaption> |
An image or diagram with a caption |
<time> |
A date or time in machine-readable form |
Beyond the layout elements, semantics also covers the everyday ones:
- Headings
<h1>to<h6>form an outline. Use them in order, with one<h1>per page, and never choose a heading level just for its size. Style the size with CSS. - Lists
<ul>,<ol>and<dl>for lists, not line breaks with dashes. - Buttons and links. Use
<button>for actions and<a href>for navigation. A clickable<div>has no keyboard support, focus handling or role unless you rebuild all of it. - Tables for tabular data only, with
<th>headers and a<caption>. - Forms. Pair every input with a
<label>, and group related fields with<fieldset>and<legend>.
A short rule of thumb: pick the element whose meaning matches the content, and use <div> and <span> only when nothing else fits.
Why semantics pay off
Accessibility. Screen readers expose landmarks, headings and lists, so users can jump around a page quickly. The W3C's WAI tutorials show how structure maps to assistive technology. Semantic elements also bring keyboard behaviour for free: a <button> is focusable and responds to Enter and Space with no extra code.
SEO. Search engines parse structure to understand a page. Clear headings, lists and article boundaries help them identify the main content and its topics. Semantics will not rescue thin content, but it removes ambiguity.
Maintainability. Names like <nav> and <article> document themselves, so new team members find their way faster. Fewer wrapper <div> elements also means less CSS fighting.
Resilience. Browsers apply sensible default styles and behaviour to semantic elements. Reader modes, translation tools and other user agents rely on them.
Real-world use cases
Inspecting minified or generated HTML. Server-rendered output, email templates and copied page sources are often a single line. Formatting them is the first step in debugging.
Reviewing templates. Before a code review, normalise indentation so the diff shows real changes instead of whitespace.
Auditing accessibility. Reading well-indented markup makes it easier to spot a missing label, a skipped heading level or a <div> doing a <button>'s job.
Cleaning up CMS or WYSIWYG output. Editors often produce deeply nested wrapper elements and inline styles. Formatting reveals the clutter, and you can then simplify it.
Teaching and documentation. Clear examples help learners focus on structure.
Common mistakes
- Div soup. Wrapping everything in
<div>loses all meaning. Replace wrappers with real elements. - Skipped or misused headings. Going from
<h1>to<h4>, or using<h3>because it looks right, breaks the outline. - Missing
alttext. Meaningful images need a description, and decorative ones need an emptyalt=""so screen readers skip them. - Clickable non-interactive elements. A
<div onclick>is invisible to keyboards and assistive tools. - Using tables for layout. Reserve tables for data. Use CSS grid or flexbox for layout.
- Inline styles and presentational tags. Keep style in CSS. Elements such as
<b>and<i>should carry meaning, or be replaced by<strong>and<em>or CSS. - Duplicate IDs. An
idmust be unique in a document, or scripts, links and labels misbehave. - Overusing ARIA. ARIA attributes patch gaps in semantics, but native elements are better. The first rule of ARIA is to avoid it when a native element exists.
Step-by-step: format HTML with DevUtilX
For a quick clean-up with no setup, use the DevUtilX HTML Formatter. It runs in your browser.
- Open the HTML formatter tool.
- Paste your messy or minified HTML into the input editor.
- Choose your indentation.
- Run the formatter and review the structured output.
- Copy the result into your project.
Your markup is processed locally and not uploaded. Once the code is readable, check it with the HTML Validator, and when you are ready for production use the HTML Minifier to reduce the size.
Validating and automating
A formatter will not tell you that a tag is unclosed or an attribute is invalid. A validator will. The W3C Nu Html Checker checks markup against the standard, and our guide on HTML validation goes deeper.
For a project, automate the routine work:
Format with Prettier. Prettier formats HTML as well as JavaScript and CSS. A short configuration keeps style consistent. Our guide to JavaScript code formatting covers the tooling.
Lint accessibility. Linters such as eslint-plugin-jsx-a11y (for JSX) or HTMLHint (for plain HTML) flag missing alt text, invalid roles and other issues as you type.
Share editor settings. An .editorconfig file keeps indentation consistent across editors.
Check in CI. Run the formatter in check mode, and a validator or accessibility scanner, on every pull request.
Keep the usual split of duties: the formatter owns layout, and linters and validators own correctness.
Best practices
- Start from the outline. Decide the page's headings and landmarks first, then fill in content.
- Prefer native elements. Choose
<button>,<nav>,<label>and friends before reaching for ARIA or scripts. - One
<h1>and one<main>per page. Keep heading levels in order. - Always set
langand a descriptive<title>. - Give every image and form control a text alternative.
- Keep markup lean. Remove wrapper elements that serve no purpose.
- Separate concerns. Structure in HTML, presentation in CSS, behaviour in JavaScript.
- Format in source, minify in the build. Keep readable files in version control and let the build compress them.
- Test with a keyboard and a screen reader. Five minutes of tabbing through a page reveals many problems.
Comparison and alternatives
HTML is not the only way to write markup, but all alternatives compile to it. If you use a template language, the same semantic rules apply to the output.
| Approach | Strength | Trade-off |
|---|---|---|
| Hand-written HTML | Full control, no build step | Repetition on large sites |
| Template engines (Pug, Haml, Nunjucks) | Less typing, includes and logic | Build step; output still needs review |
| Markdown | Fast for content | Limited structure; relies on a renderer |
| JSX and component frameworks | Reusable components | Easy to produce div soup without discipline |
| WYSIWYG editors | Easy for non-developers | Often noisy, non-semantic output |
Whatever produces your HTML, view the final output regularly. The browser reads the output, not your source template.
How browsers actually read your HTML
Formatting and semantics both make more sense once you know what a browser does with the text you give it. The parser does not validate your markup and reject it. It follows an error-recovery algorithm defined in the WHATWG specification, and that algorithm always produces a document tree, however broken the input.
The result is a DOM, a tree of nodes. Your indentation never reaches it. Two spaces, four spaces and a tab all vanish, apart from whitespace text nodes that sit between elements. That is why formatting is purely a human concern, and why a formatter can safely rewrite layout in most places.
Recovery rules explain several bugs that confuse beginners:
- Implied end tags. A new
<p>closes an open<p>. A new<li>closes an open<li>. This is why omitting closing tags works, and why a stray tag can end an element earlier than you intended. - Content model corrections. A
<p>cannot contain a<div>. If you write a<div>inside a paragraph, the parser closes the paragraph first, so the<div>becomes a sibling. Your CSS selectors then match a tree that differs from the one in your source. - Foster parenting. If you put stray text or a
<div>directly inside a<table>, the parser moves it to just before the table. Content seems to jump out of place. - Unknown elements. A tag the browser does not recognise becomes a generic element with no meaning. A custom element name must contain a hyphen, as in
<site-header>, to be valid.
The practical lesson: the DOM you inspect in developer tools is the truth, and your source file is only a proposal. When something renders oddly, compare the two. A formatter helps because well-indented source makes a misplaced closing tag visible, but the Elements panel in your browser shows what the parser did with it.
The accessibility tree
Browsers build a second tree from the DOM, the accessibility tree. Each node has a role, a name, a state and sometimes a description. Screen readers and other assistive tools read this tree, not your pixels.
A <button> becomes a node with the role button. Its name comes from its content. A <nav> becomes a navigation landmark. A <div> with a click handler becomes a generic node with no role, and no amount of CSS changes that. This is the mechanical reason semantics matter: they feed the accessibility tree.
You can inspect it directly. Chromium-based browsers and Firefox both include an accessibility panel in their developer tools. Select an element and read its computed role and name. If the name is empty on a control, a screen reader user hears only "button" or nothing useful.
A short history of why the web has semantic elements
Early HTML mixed structure and appearance. Tags such as <font>, <center> and <b> described how text should look. As CSS matured, the community moved toward a split: HTML says what content is, and CSS says how it looks. That split is the foundation of everything in this article.
HTML 4 gave authors headings, lists, tables and forms, but no way to mark up a page region. Authors filled the gap with <div id="header"> and <div id="nav">. These ids were conventions with no meaning to software. Around the same time, XHTML tried to enforce strict, XML-style syntax. It never displaced forgiving HTML parsing in practice, and the WHATWG formed to continue evolving HTML itself.
HTML5 standardised the parser's error handling, so every browser builds the same tree from the same broken input. It also added the region elements covered earlier, along with <audio>, <video>, <canvas> and richer form controls. The WHATWG now maintains HTML as a living standard with no version number, so new features arrive continuously rather than in big releases.
Knowing this history helps with legacy code. If you meet <font>, <center> or table-based layouts, you are looking at the pre-CSS era. If you meet XHTML-style <br /> and lowercase quoted attributes, you are looking at habits that survived because they are tidy. Both are valid choices in modern HTML, but only one of them carries meaning.
Landmarks and how they map to roles
The region elements do not all behave the same way. Some map to a landmark role only under certain conditions, and the details matter when you build page templates.
| Element | Landmark role | Condition |
|---|---|---|
<header> |
banner | Only when it is not nested inside <article>, <section>, <aside>, <nav> or <main> |
<footer> |
contentinfo | Same condition as <header> |
<nav> |
navigation | Always |
<main> |
main | Always |
<aside> |
complementary | Always |
<section> |
region | Only when it has an accessible name |
<form> |
form | Only when it has an accessible name |
Two consequences follow. First, a <header> inside an <article> is just a heading group for that article. It does not create a second page-level banner. Second, a <section> with no name is effectively a generic container to assistive technology. Give it aria-labelledby pointing at its heading if you want it to be a navigable region:
<section aria-labelledby="pricing-title">
<h2 id="pricing-title">Pricing</h2>
<p>Plans for individuals and teams.</p>
</section>
When a page has more than one <nav>, label each one. A header menu and a footer menu both announce as "navigation" unless you add aria-label="Main" and aria-label="Footer". Keep labels short and avoid the word "navigation" in them, since the role already says it.
Do not over-landmark. If every block is a landmark, the list a screen reader user hears becomes noise. A typical page needs a banner, one or two navigations, a main region and a content footer. Add more only where a user would plausibly want to jump to them.
Skip links
Keyboard users have to tab through every link in your header before they reach the content. A skip link fixes that. It is the first focusable element on the page and jumps to <main>:
<body>
<a class="skip-link" href="#main">Skip to main content</a>
<header>...</header>
<main id="main" tabindex="-1">...</main>
</body>
Hide the link visually until it receives focus, but never with display: none, which removes it from the tab order. The tabindex="-1" on <main> lets it receive focus programmatically in browsers that do not move focus on fragment navigation.
Headings, outlines and a common misconception
Older drafts of the HTML specification described an outline algorithm. Nested <section> elements would reset heading levels, so an <h1> inside a section would act as an <h2>. No browser or assistive technology ever implemented it reliably, and the specification text for it has since been removed.
The consequence is simple. Heading levels are what you write, not what a sectioning element implies. Pick each level to reflect the document structure, and keep them in order. This matters most in component-based code, where a reusable card might hardcode an <h3> and then appear on pages where the surrounding heading is an <h1>. Skipped levels result.
There are three workable fixes for reusable components:
- Accept a heading level as a parameter, so the page decides.
- Use CSS for the visual size and keep the level sensible for the typical context.
- Review the full outline with a tool, since components compose in ways no single file shows.
To review an outline quickly, run this snippet in the browser console. It prints each heading indented by its level:
document.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach((h) => {
const level = Number(h.tagName[1]);
console.log(' '.repeat(level - 1) + 'h' + level + ' ' + h.textContent.trim());
});
A clean outline reads like a table of contents. If you see an h4 with no h3 above it, or three h1 lines, fix it.
Walkthrough: from div soup to semantic markup
Here is a realistic fragment, the kind that comes out of a CMS or a quick prototype.
<div class="page">
<div class="top"><div class="logo">Acme</div>
<div class="links"><span onclick="go('/')">Home</span><span onclick="go('/docs')">Docs</span></div></div>
<div class="content">
<div class="title">Getting started</div>
<div class="date">12 March 2025</div>
<div class="text">Install the package, then run the setup command.</div>
<div class="btn" onclick="download()">Download</div>
</div>
<div class="bottom">Copyright Acme</div>
</div>
Work through it in passes. Do not try to fix everything at once.
Pass 1: format. Run it through a formatter so the structure is visible. You now see a header, a content block and a footer, all unnamed.
Pass 2: replace containers with landmarks. .top becomes <header>, .links becomes a <nav> containing a list, .content becomes <main>, and .bottom becomes <footer>. The outer .page wrapper may no longer be needed; <body> can often do its job.
Pass 3: fix the content. .title is a heading, so it becomes an <h1>. .date becomes a <time> with a machine-readable value. .text becomes a <p>. If this is a standalone piece, wrap title, date and text in an <article>.
Pass 4: fix the interactive parts. The clickable <span> elements are links, because they navigate. They become <a href>, which also restores middle-click, open in new tab and visible focus. The .btn performs an action, so it becomes a <button type="button">.
Pass 5: move behaviour and style out. Delete the inline onclick attributes, attach event listeners in script, and keep presentation in CSS classes.
<header>
<a class="logo" href="/">Acme</a>
<nav aria-label="Main">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/docs">Docs</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h1>Getting started</h1>
<p><time datetime="2025-03-12">12 March 2025</time></p>
<p>Install the package, then run the setup command.</p>
<button type="button" id="download">Download</button>
</article>
</main>
<footer>
<p>Copyright Acme</p>
</footer>
The result has fewer elements, no inline handlers, and every part has a name a machine understands. Notice that nothing here required ARIA beyond one label on the navigation. Native elements did the work.
Run the same refactor on a copy of a real template once, and the pattern becomes habit: format, landmarks, content, controls, separation.
Forms: where semantics earn their keep
Forms are the part of a page where the cost of bad markup is highest, because users must complete them. Native form markup gives you labelling, validation, autofill and keyboard behaviour with no script.
Associate labels explicitly. Either wrap the input in the <label>, or connect them with for and id. A placeholder is not a label. It disappears when the user types, and it often has poor contrast.
<form action="/subscribe" method="post">
<fieldset>
<legend>Newsletter</legend>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required />
<p id="email-hint">We send one message a month.</p>
</fieldset>
<button type="submit">Subscribe</button>
</form>
Choose the right input type. type="email", type="tel", type="url" and type="number" bring the appropriate on-screen keyboard on phones and basic validation in the browser. Use the autocomplete attribute with standard tokens so password managers and autofill can help.
Link hints and errors. Use aria-describedby to point an input at its hint or error text, so a screen reader reads it with the field. Mark invalid fields with aria-invalid="true" once you have validated them.
Set the button type. Inside a form, a <button> defaults to type="submit". A button that should only run script needs type="button", or it will submit the form unexpectedly. This is one of the most common small bugs in form markup.
Use <fieldset> for groups. Radio buttons and checkboxes that answer one question belong in a fieldset with a legend. Without it, a screen reader user hears the options but not the question.
Interactive elements you may not need JavaScript for
Several native elements replace patterns that developers often build from scratch.
<details>and<summary>give you a disclosure widget with built-in keyboard support and state. Use it for FAQs and expandable notes.<dialog>provides a modal or non-modal dialog. Opening it with theshowModal()method traps focus, makes the rest of the page inert and closes on Escape.<datalist>attaches suggestions to a text input.- The
popoverattribute turns an element into a lightweight overlay controlled from a button. <template>holds inert markup that scripts can clone, which avoids building HTML from strings.
Browser support for the newer features varies with the version, so check the MDN compatibility tables on each element's page before relying on one. Where support is partial, the usual strategy is progressive enhancement: start from content that works without the feature.
A hand-rolled accordion needs focus management, state attributes and key handling. <details> needs none of that. Before you write a component, search the HTML specification for an element that already does the job.
Formatting traps: where a formatter can hurt you
A good formatter is safe in most of a document and risky in a few specific places. Know them.
<pre> and <textarea>. Whitespace inside these elements is preserved and visible. Re-indenting their contents changes what the user sees. Good formatters leave them alone, but verify, especially if your code samples sit inside <pre><code>.
Inline elements. Take <a>one</a><a>two</a>. There is no space between the links. If a formatter breaks the line between them, a space appears. Prettier's htmlWhitespaceSensitivity option controls this. The default value, css, respects each element's default display value. The value strict treats all whitespace as significant, and ignore treats it as insignificant.
Inline-block layouts. Older layouts that rely on the gap between inline-block items can change when whitespace moves. Prefer flexbox or grid and the problem disappears.
Embedded languages. Inline <script> and <style> blocks contain JavaScript and CSS. Some formatters reformat them with the correct language rules, and some leave them untouched. Check what yours does.
Templating syntax. Server templates mix tags such as {% if %} or <?php ?> into HTML. A plain HTML formatter may mangle them, because the combined file is not valid HTML. Use a formatter or plugin that understands your template language, or format only the rendered output.
Conditional comments and special comments. Email templates in particular rely on comments that clients interpret. A formatter that moves or rewraps them can break the email in one client while looking fine in another.
When a formatter does something odd, most tools offer an ignore comment for a block. Use it sparingly, and add a note explaining why.
Setting up a project, step by step
Here is a minimal, working setup for a plain HTML project. It combines the pieces mentioned earlier.
Step 1: EditorConfig. Create .editorconfig at the root:
root = true
[*.html]
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
Most editors read it natively or through a plugin. Note that trim_trailing_whitespace is safe in HTML, but be careful if your <pre> blocks depend on trailing spaces.
Step 2: Prettier. Install it as a development dependency and add a configuration file:
{
"printWidth": 100,
"tabWidth": 2,
"htmlWhitespaceSensitivity": "css",
"singleAttributePerLine": false
}
Add scripts to package.json so everyone runs the same commands:
{
"scripts": {
"format": "prettier --write \"**/*.html\"",
"format:check": "prettier --check \"**/*.html\""
}
}
Step 3: HTMLHint. Add a .htmlhintrc with rules for the issues that bite most often:
{
"tagname-lowercase": true,
"attr-lowercase": true,
"attr-value-double-quotes": true,
"doctype-first": true,
"tag-pair": true,
"id-unique": true,
"alt-require": true,
"spec-char-escape": true
}
Step 4: Pre-commit hook. A tool such as Husky with lint-staged can run Prettier and HTMLHint on staged files only. This keeps commits fast and stops unformatted markup reaching the repository.
Step 5: CI. Run format:check, HTMLHint and the W3C validator in your pipeline. Fail the build on errors, and decide as a team whether warnings fail it too.
Step 6: Accessibility scan. Add an automated scanner in CI or as a browser extension in your daily workflow. Automated checks catch only part of the possible problems, so they supplement manual keyboard testing rather than replacing it.
Format before you lint. If the formatter runs first, linter output refers to the final layout, and you avoid arguments over style in review. For the same pattern applied to scripts, see our guide to JavaScript code formatting.
Security considerations
Markup is also an attack surface. Formatting does not make code safe, but semantics and careful output handling help.
Escape untrusted text. If user input appears in HTML, convert <, >, & and quotes into entities, or use a templating system that does so by default. Unescaped output is the root of cross-site scripting. The linter rule spec-char-escape catches stray special characters in static files, but it cannot protect dynamic content.
Be careful with innerHTML. Assigning a string to innerHTML parses it as markup. For plain text, use textContent. For structured insertion, create elements with the DOM API or clone a <template>.
Treat attributes as code surfaces. An attribute such as href can carry a javascript: URL, and event handler attributes run script. Validate URLs from users, and avoid inline handlers, which also makes a strict Content Security Policy possible.
Handle external links deliberately. Links that open a new tab with target="_blank" expose a reference to the opener page in older browsers. Current browsers treat such links as if rel="noopener" were set, but adding rel="noopener" costs nothing and covers older ones. Add rel="noreferrer" too if you do not want the destination to see the referring address.
Sandbox embedded content. The sandbox attribute on an <iframe> restricts what the embedded page can do. Start with it empty and add back only the permissions you need.
Add a Content Security Policy. A CSP delivered through an HTTP header limits where scripts, styles and frames can load from. It works best with clean markup that keeps script and style out of attributes, which is another reason to separate concerns.
Performance and DOM size
Whitespace is cheap, but structure is not free. The browser builds a node for every element and text run, and style and layout work grows with the size and depth of the tree.
Semantic cleanup tends to reduce node counts, because replacing three nested wrapper <div> elements with one meaningful element removes two nodes and the CSS that styled them. On a large page, that adds up, though you should measure rather than assume. The Performance panel in browser developer tools shows how long style recalculation and layout take.
A few markup habits affect perceived speed directly:
- Set
widthandheighton images. The browser reserves space before the file arrives, so content does not jump. Modern browsers use these attributes to compute an aspect ratio even when CSS resizes the image. - Use
loading="lazy"for images below the fold. Do not apply it to the main image visible on first load. - Put
<script>withdeferortype="module"so parsing is not blocked. Module scripts are deferred by default. - Order the
<head>thoughtfully. Put the character set declaration within the first 1024 bytes, and place critical stylesheets before scripts that depend on them. - Avoid giant inline data. Huge base64 images or JSON blobs make the document slow to read and diff. Link to files instead.
For the production side, such as whitespace removal and attribute trimming, see our discussion of HTML minification trade-offs.
Troubleshooting guide
Use this table when markup misbehaves. Start from the symptom.
| Symptom | Likely cause | Fix |
|---|---|---|
A <div> inside a <p> ends up outside the paragraph |
The parser closes <p> before a block element |
Use <div> or another valid container instead of <p>, or move the block outside |
| Content appears above a table | Stray content directly inside <table> was foster-parented |
Put content inside <td> or <th>, or move it outside the table |
| A gap appears between inline elements after formatting | The formatter inserted a line break between them | Raise whitespace sensitivity, or remove the break and add an ignore comment |
| Form submits when you click a helper button | Buttons default to type="submit" |
Add type="button" |
| Label click does not focus the input | for does not match the input's id, or the id is duplicated |
Match the values and make ids unique |
| Screen reader reads "button" with no name | An icon-only button has no text | Add visible text, or aria-label, or visually hidden text |
Page shows odd characters like é |
Wrong or missing character encoding | Add <meta charset="utf-8"> early in <head> and save the file as UTF-8 |
| Styles from one component leak into another | Duplicate ids, or selectors that depend on structure the parser changed | Inspect the live DOM and fix the invalid nesting |
Anchor link #section goes to the wrong place |
Two elements share the same id | Make ids unique |
| Layout differs between browsers | Quirks mode from a missing or malformed doctype | Put <!DOCTYPE html> first, with nothing before it |
Two tools solve most of these. The W3C validator reports invalid nesting and duplicate ids. The browser's Elements panel shows the tree the parser actually built. Use both before you start changing CSS.
Team conventions and a review checklist
A style guide only works when it is short enough to remember and enforced by tools. Decide a few things once, write them down and let the formatter handle the rest.
Decide:
- Indentation width and line length.
- Whether void elements use a trailing slash (
<br>or<br />). Either is valid in HTML, so pick one. - Class naming approach, and whether classes may describe appearance.
- Who owns shared components and their heading levels.
- Which accessibility checks are mandatory before merge.
Review checklist for a pull request:
- Does the page have one
<h1>, and do headings descend without gaps? - Are landmarks present and labelled where duplicated?
- Does every control have an accessible name?
- Does every image have appropriate
alttext? - Are all interactive elements native, or do custom ones have full keyboard support?
- Can you complete the main task using only a keyboard?
- Do ids stay unique across the final rendered page?
- Does the validator report zero errors?
Keep the checklist in the repository's contributing guide. Short checklists get used, long ones get ignored.
For the diff step of review, consider the code diff guide. Comparing formatted output before and after a refactor makes accidental changes easy to spot.
Migrating a legacy site gradually
Rewriting every template at once is rarely realistic. A gradual path works better.
Start by formatting everything in one commit. A pure formatting commit, with no logic changes, gives you a clean baseline. Tell reviewers it is formatting only, and consider recording it in a file that your version control tool can ignore when showing blame.
Then fix the template shell. The layout used by every page, usually header, navigation, footer and <head>, gives the biggest return. Convert it to landmarks, add lang and a skip link, and every page improves at once.
Next, tackle high-traffic and high-risk pages. Forms, checkout flows and login screens matter most for accessibility. Fix labels, error messages and button types there first.
Replace fake controls. Search for onclick on non-interactive elements and convert each to a link or button. This is a mechanical change with a visible benefit.
Add automated checks last, in warning mode. Turn on the validator and linter as warnings, reduce the count over time, then switch them to errors. A check that fails on day one of adoption will simply be disabled.
Track progress with a simple count of violations per rule. A number that falls every month keeps the effort alive better than a one-off cleanup.
FAQ
Does HTML formatting affect SEO or page speed?
Not in any meaningful way. Whitespace is a tiny part of the payload, and search engines ignore layout. Semantics and content quality matter far more. Minify for production if you want to save bytes.
Should I use <section> or <div>?
Use <section> when the content is a thematic group that would have a heading. Use <div> when you only need a styling or scripting hook.
Can I have more than one <h1>?
The specification allows it in some contexts, but one <h1> per page gives the clearest outline for screen readers and search engines.
Do I need to close <p> and <li> tags?
The parser can infer them, but explicit closing tags make the structure obvious and avoid subtle bugs. Most style guides require them.
Is ARIA better than semantic HTML?
No. Native elements come with built-in roles and keyboard behaviour. Use ARIA only to fill gaps that native HTML cannot.
Will a formatter change how my page looks?
Usually not, but inline elements are sensitive to whitespace, so a reflow can add or remove a visible space. Review changes around inline content.
Why does my <div> jump out of a <p> in the DOM?
The specification says a paragraph can only contain phrasing content. When the parser meets a block element inside an open <p>, it closes the paragraph first. Inspect the live DOM to see the result, and use a valid container.
Should void elements end with a slash?
Both <br> and <br /> are valid in HTML. The slash has no effect. Choose one style, let the formatter enforce it, and be consistent.
Is <section> a landmark?
Only when it has an accessible name, for example through aria-labelledby. Without a name it behaves as a generic grouping element for assistive technology.
When should I use <b> or <i>?
Use them for text that is stylistically offset without extra importance or emphasis, such as a product name or a technical term. Use <strong> and <em> when the meaning is importance or stress.
Does indentation size matter?
Not to the browser. Choose a width your team agrees on, record it in .editorconfig and let tools apply it. Two spaces is common because deep nesting stays readable.
Can I format HTML that contains template tags?
Only with a tool that understands your template language. Otherwise format the rendered output, or exclude the template files and rely on review.
Do I need <meta charset="utf-8">?
Yes, in nearly every case. Place it early in <head>, and save the file as UTF-8, so the browser decodes text correctly.
How do I make an icon-only button accessible?
Give it a name through visually hidden text inside the button, or an aria-label. Hide the decorative icon itself from assistive technology.
How often should I run a validator?
Run it in CI on every pull request. It is quick, and early feedback on invalid nesting is cheaper than debugging it in production.
Conclusion
Good HTML has two qualities: it is readable to developers and meaningful to machines. Format it consistently, automate that formatting, and choose elements by their meaning rather than their default appearance. Landmarks, proper headings, real buttons and labelled inputs make a page accessible, easier to maintain and clearer to search engines. For a fast clean-up, try the HTML Formatter. To continue, read our guide on CSS formatting and architecture, which pairs naturally with clean markup.
Further reading
Try the tools
Clean up and format your HTML code effortlessly. This tool applies proper indentation and ensures a well-organized tag structure, which greatly improves readability and helps in maintaining clean, professional-grade markup.
Check your HTML markup for compliance with W3C standards. This tool helps you identify and fix errors, ensuring your website is accessible and renders correctly across all browsers, improving user experience.
Minify your HTML files by removing unnecessary whitespace, comments, and other redundant characters. This results in smaller file sizes, which can significantly improve your website's loading performance and user experience.
.jpg)
.jpg)
.jpg)