Enterprise HTML Coding Standards
By the end of this lesson you will be able to write a team HTML coding standard with clear must and should rules, turn most of those rules into Prettier, EditorConfig and html-validate settings, and review a pull request against a short checklist.
What you should know first: the readable-HTML habits in HTML Validation Using W3C, BEM classes and data-js hooks from Professional HTML Architecture, required head tags from Metadata at Scale: Head Templates, and the tools themselves from Automated HTML Validation. This lesson does not teach the tools again. It decides what the rules are and writes them down.
Why a written standard
A coding standard is like a cricket team's batting order: decided before the match, written down, and followed by everyone, so nobody argues at the crease.
Without one, every pull request becomes a debate about quotes and spaces, and real bugs hide in the noise.
A good standard has three properties:
- Every rule has a reason. "Boolean attributes have no value, because
required="false"still makes a field required" teaches something. "We like it" does not. - Every rule has a strength. Teams borrow the words must (breaking it blocks the merge), should (break it only with a written reason) and may (a free choice) from RFC 2119, the document that defines these words for standards.
- Every rule has an enforcer. A tool, or a named line in the review checklist. A rule that nobody checks slowly stops existing.
Give each rule a short id, such as FMT-02, so reviewers can write "breaks NAME-01".
Formatting and syntax
Let a formatter own formatting. Nobody should hand-indent HTML in 2026. Here is the team's Prettier file, .prettierrc.json, checked against Prettier 3.9 (the 3.x line was current in November 2026):
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"endOfLine": "lf",
"htmlWhitespaceSensitivity": "css",
"bracketSameLine": false,
"singleAttributePerLine": false
}printWidth is where Prettier starts wrapping. htmlWhitespaceSensitivity: "css" respects inline and block elements, so it never adds a visible space inside a sentence.
Next, EditorConfig sets the basics in almost every editor before Prettier even runs. Save this as .editorconfig in the project root:
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = falseroot = true tells editors to stop looking in parent folders. Prettier's command line also reads .editorconfig (indent, line ending and line length), but .prettierrc.json wins where both set a value. Keep the two files in agreement.
The syntax rules then read like this:
| Id | Rule | Strength | Enforced by |
|---|---|---|---|
| FMT-01 | Two-space indent, LF line endings, UTF-8 files | must | EditorConfig, Prettier |
| FMT-02 | Lowercase element and attribute names | must | Prettier, parser |
| FMT-03 | Double quotes around every attribute value | must | Prettier |
| FMT-04 | Boolean attributes written alone: required, not required="required" | must | html-validate |
| FMT-05 | Void elements follow the formatter's style (<img /> with Prettier) | must | Prettier |
| FMT-06 | Attribute order: id, class, then type/name/href/src/for/value, then alt/title, then role/aria-*, then data-*, then boolean attributes | should | Review |
FMT-05 surprises people: Prettier writes <!doctype html> in lowercase and adds /> to void elements. Both are valid HTML. Let the formatter choose, and tell the linter to accept it (shown below). FMT-06 has no tool behind it, because neither Prettier nor html-validate checks attribute order, so it is a review item.
Naming rules
| Id | Rule | Strength |
|---|---|---|
| NAME-01 | Classes use BEM in kebab case: fee-table__row--paid | must |
| NAME-02 | id values are kebab case and exist only for fragment links, <label for> and ARIA references | must |
| NAME-03 | Scripts select data-js hooks, never styling classes | must |
| NAME-04 | Custom data attributes are kebab case and say what they hold: data-batch-id, not data-x | should |
| NAME-05 | State lives in native or ARIA attributes (hidden, open, aria-expanded), not invented classes | should |
Semantics, accessibility and the head
These rules protect users, so most of them are must:
- A11Y-01 (must): one
<main>, landmarks where they fit, headings in order without skipped levels. - A11Y-02 (must): every
<img>hasalt; decorative images usealt="". - A11Y-03 (must): every form control has a connected
<label>; placeholders never replace labels. - A11Y-04 (must): actions use
<button type="...">, navigation uses<a href>. No clickable<div>. - A11Y-05 (must): no positive
tabindex. Only0or-1. - A11Y-06 (should): prefer native elements (
<dialog>,<details>) over ARIA rebuilds.
Every page head must contain, in this order: <meta charset="utf-8"> as the first child, the viewport tag without user-scalable=no or maximum-scale, a unique <title>, a meta description, and a canonical link on public pages. <html> must carry the right lang, such as en-IN or hi. The head template produces these, so check the template once and every page inherits it.
Comments, TODOs and banned patterns
HTML comments travel to every visitor. Anyone in Lucknow or Kochi can press Ctrl+U and read them. So the comment policy is strict:
- CMT-01 (must): no passwords, internal URLs, customer names or ticket discussions in HTML comments. Use your template language's comments (
{{-- --}}in Blade,<?php /* */ ?>in PHP), which never reach the browser. - CMT-02 (should): comments explain why, not what.
<!-- Second h2 kept for the Hindi page's outline -->helps;<!-- heading -->does not. - CMT-03 (must): a TODO has an owner and a ticket:
TODO(priya, WEB-482): remove after Diwali sale. A TODO without a ticket fails review. - CMT-04 (must): no commented-out markup. Git remembers old code for you.
Banned patterns are the "never" list. Each one has a better replacement:
| Banned | Use instead |
|---|---|
style="..." attributes | A class in the stylesheet |
onclick="..." and other on* attributes | addEventListener with a data-js hook |
href="javascript:..." | A <button> |
<br> or for spacing | CSS margins and gaps |
Tables for layout, <font>, <center> | Grid, Flexbox, CSS |
Third-party scripts without integrity | Subresource Integrity, see SRI |
Step 1: enforce the standard with html-validate
Most rules above map to html-validate rules. Save this as .htmlvalidate.json. It was tested with html-validate 11.17 (the 11.x line was current in November 2026):
{
"extends": ["html-validate:recommended", "html-validate:prettier"],
"rules": {
"attribute-boolean-style": ["error", { "style": "omit" }],
"id-pattern": ["error", { "pattern": "kebabcase" }],
"class-pattern": ["error", { "pattern": "bem" }],
"heading-level": "error",
"require-sri": ["error", { "target": "crossorigin" }]
}
}The two presets work as a pair. recommended switches on the standard checks, including no-inline-style. The prettier preset switches off three rules that clash with Prettier's output (quote style, doctype case and void style), because the formatter already owns those. Then id-pattern and class-pattern enforce NAME-01 and NAME-02, heading-level enforces the heading order, and require-sri with target: "crossorigin" demands integrity only on files from other domains.
Kabir's coaching centre in Pune has a fees page that breaks several rules. Save it as dist/fees.html:
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fees | Kabir's Coaching Centre, Pune</title>
<script src="https://cdn.example.com/menu.js"></script>
</head>
<body>
<h1>Fees</h1>
<h3 class="feeTable">Class 10 batch</h3>
<p id="Fee_Note" style="color: red">Fees are due by 10 June.</p>
<img src="fees.png" alt="Fee chart" width="600" height="400" />
<label for="email">Email</label>
<input type="email" id="email" required="required">
<button>Send</button>
</body>
</html>npx html-validate dist/fees.htmldist/fees.html 7:4 error SRI "integrity" attribute is required on <script> element require-sri 11:4 error Heading level can only increase by one, expected <h2> but got <h3> heading-level 11:14 error class "feeTable" does not match the configured pattern "bem" class-pattern 12:10 error id "Fee_Note" does not match the configured pattern "kebabcase" id-pattern 12:20 error Inline style is not allowed no-inline-style 15:34 error Attribute "required" should omit value attribute-boolean-style 16:4 error <button> is missing recommended "type" attribute no-implicit-button-type ✖ 7 problems (7 errors, 0 warnings)
The real output prints the full file path and ends with a link for each rule; both are shortened here. Seven rules, seven errors, no human effort. Then check formatting:
npx prettier --check "src/**/*.html"Checking formatting... [warn] src/fees.html [warn] Code style issues found in the above file. Run Prettier with --write to fix.
Running prettier --write re-indents the page, lowercases the doctype and adds /> to the <meta> and <input> tags. After you fix the seven errors by hand, both commands pass. The npm scripts and CI workflow from Automated HTML Validation then run them on every pull request.
Step 2: a team rules checker in the browser
Some rules can be checked on the parsed page itself. The tool below holds a page in a text box, parses it with DOMParser (which turns text into a document without showing it), and reports rule ids from the standard. Edit the page and press Check again.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Team rules checker</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
textarea { inline-size: 100%; block-size: 14rem; font-family: monospace; }
.report li { margin-block: 4px; }
</style>
</head>
<body>
<h1>Team rules checker</h1>
<label for="source">Page to check</label>
<textarea id="source"><!DOCTYPE html>
<HTML>
<head>
<title>Results 2026 | Meera Tutorials, Jaipur</title>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, user-scalable=no">
</head>
<body>
<h1 class="Page-Title">Results</h1>
<p id="topScore" class="result-card__name--gold">Ananya: 98.4%</p>
<img src="topper.jpg">
<div onclick="showMore()" tabindex="3">More results</div>
<input type="checkbox" checked="checked" data-js="Toggle">
</body>
</HTML></textarea>
<p><button type="button" id="check">Check</button></p>
<ol class="report" id="report" aria-live="polite"></ol>
<script>
const bem = /^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z0-9]+(-[a-z0-9]+)*)?(--[a-z0-9]+(-[a-z0-9]+)*){0,2}$/;
const kebab = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
const booleans = ["required", "disabled", "checked", "hidden", "readonly", "multiple", "open", "selected", "async", "defer"];
function check(doc) {
const found = [];
const add = (id, text) => found.push(`${id}: ${text}`);
if (!doc.documentElement.lang) add("HEAD-01", "<html> has no lang");
const first = doc.head.firstElementChild;
if (!first || !first.matches("meta[charset]")) add("HEAD-02", "<meta charset> is not the first element in <head>");
const vp = doc.querySelector('meta[name="viewport"]')?.content ?? "";
if (/user-scalable\s*=\s*no|maximum-scale/.test(vp)) add("HEAD-03", "viewport blocks zooming");
if (!doc.querySelector('meta[name="description"]')) add("HEAD-04", "no meta description");
for (const el of doc.body.querySelectorAll("*")) {
const tag = `<${el.localName}>`;
for (const c of el.classList) if (!bem.test(c)) add("NAME-01", `class "${c}" on ${tag} is not BEM`);
if (el.id && !kebab.test(el.id)) add("NAME-02", `id "${el.id}" is not kebab case`);
if (el.dataset.js && !kebab.test(el.dataset.js)) add("NAME-03", `data-js="${el.dataset.js}" is not kebab case`);
if (el.localName === "img" && !el.hasAttribute("alt")) add("A11Y-02", `${tag} has no alt`);
if (Number(el.getAttribute("tabindex")) > 0) add("A11Y-05", `positive tabindex on ${tag}`);
if (el.hasAttribute("style")) add("BAN-01", `style attribute on ${tag}`);
for (const a of el.attributes) {
if (a.name.startsWith("on")) add("BAN-02", `${a.name} attribute on ${tag}`);
if (booleans.includes(a.name) && a.value !== "") add("FMT-04", `${a.name}="${a.value}" on ${tag}`);
}
}
return found;
}
document.querySelector("#check").addEventListener("click", () => {
const doc = new DOMParser().parseFromString(document.querySelector("#source").value, "text/html");
const report = document.querySelector("#report");
report.replaceChildren();
const found = check(doc);
for (const text of found.length ? found : ["No rule broken. Well done."]) {
const li = document.createElement("li");
li.textContent = text;
report.append(li);
}
});
document.querySelector("#check").click();
</script>
</body>
</html>You should see eleven findings, from HEAD-01 to FMT-04. Notice what is missing: nothing complains about <HTML> in capitals or charset='utf-8' in single quotes. The parser lowercased the names and threw the quotes away before your script saw the page. Source-level rules such as FMT-02 and FMT-03 need a tool that reads the raw text, which is exactly why Prettier and html-validate exist.
Step 3: the code review checklist
The last enforcer is a person. Keep the checklist short and only for things tools cannot see. Here it is as a small page a reviewer can use: the Approve button unlocks only when every must item is ticked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML review checklist</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 40rem; }
fieldset { margin-block: 12px; border-radius: 8px; }
label { display: block; margin-block: 6px; }
</style>
</head>
<body>
<h1>HTML review checklist</h1>
<p>Pull request: WEB-482, Diwali offer banner. Lint and format checks: passed.</p>
<form id="review">
<fieldset>
<legend>Must (blocks the merge)</legend>
<label><input type="checkbox" name="must"> Each element matches its meaning (button acts, link goes)</label>
<label><input type="checkbox" name="must"> Alt text describes the image's purpose, not its file name</label>
<label><input type="checkbox" name="must"> Heading levels fit the page this component lands on</label>
<label><input type="checkbox" name="must"> No secrets or internal notes in HTML comments</label>
<label><input type="checkbox" name="must"> Every TODO has an owner and a ticket</label>
</fieldset>
<fieldset>
<legend>Should (discuss if not)</legend>
<label><input type="checkbox" name="should"> Attribute order follows FMT-06</label>
<label><input type="checkbox" name="should"> Native elements used before ARIA rebuilds</label>
<label><input type="checkbox" name="should"> New component added to the inventory</label>
</fieldset>
<p><progress id="bar" max="5" value="0"></progress> <span id="count">0 of 5 must items</span></p>
<button type="submit" id="approve" disabled>Approve</button>
<output id="result" for="approve"></output>
</form>
<script>
const form = document.querySelector("#review");
const musts = form.querySelectorAll('[name="must"]');
form.addEventListener("change", () => {
const done = [...musts].filter((box) => box.checked).length;
document.querySelector("#bar").value = done;
document.querySelector("#count").textContent = `${done} of ${musts.length} must items`;
document.querySelector("#approve").disabled = done < musts.length;
});
form.addEventListener("submit", (event) => {
event.preventDefault();
const open = [...form.querySelectorAll('[name="should"]')].filter((box) => !box.checked).length;
document.querySelector("#result").textContent =
open ? ` Approved with ${open} should item(s) to discuss.` : " Approved.";
});
</script>
</body>
</html>Tick the five must items and the button unlocks. Approve with a should item unticked and the result says how many need a comment in the review.
Common mistakes
- A standard with no enforcer. If neither a tool nor the checklist checks a rule, delete it or automate it.
- Formatter and linter disagreeing. Prettier writes
<img />and a strictvoid-stylerule rejects it. Extendhtml-validate:prettier. - Secrets in HTML comments. They ship to every browser. Use template comments.
- Every rule as "must". Then nothing feels important. Keep "must" for correctness and accessibility.
Interview questions
1. Why do teams write a coding standard if the browser accepts messy HTML anyway?
Browsers repair bad markup silently, and different repairs can hide bugs and accessibility problems. A standard makes everyone's code look the same, so reviews focus on meaning instead of style. It also lets tools enforce rules automatically on every change.
2. What is the difference between Prettier and html-validate?
Prettier is a formatter: it changes indentation, quotes and line breaks but never meaning. html-validate is a linter: it reports errors such as duplicate ids, bad nesting or names that break your patterns. Teams use both, and extend html-validate:prettier so the linter does not reject the formatter's style.
3. How would you enforce BEM class names and kebab-case ids automatically?
In .htmlvalidate.json, set class-pattern to { "pattern": "bem" } and id-pattern to { "pattern": "kebabcase" }. Run the linter on the built HTML in an npm script and in CI, so a pull request with class="feeTable" fails before merge.
4. What should never go into an HTML comment?
Anything private: credentials, internal URLs, customer data or team discussions. HTML comments are sent to every visitor and are visible in View Source. Use server-side template comments for notes that must stay private.
5. What do must, should and may mean in a standard?
They come from RFC 2119. A must rule is required, so breaking it blocks the merge. A should rule is strongly recommended and may be broken only with a written reason. A may rule is optional.
Key points
- A good standard gives every rule an id, a reason, a strength (must, should, may) and an enforcer.
- Let Prettier own formatting and EditorConfig set editor basics; keep the two files in agreement.
- Encode naming and correctness rules in
.htmlvalidate.json, extendingrecommendedplusprettier. - The parser normalises case and quotes, so source rules need tools that read raw text.
- HTML comments are public; TODOs need an owner and a ticket; commented-out code is not allowed.
- Keep the human review checklist short and only for what tools cannot judge.
Exercise
Write a one-page HTML standard for Rohan's travel agency in Kochi. Include at least three FMT rules, three NAME rules, three A11Y rules and a banned-patterns table, each with an id, a strength and an enforcer. Then write the .editorconfig, .prettierrc.json and .htmlvalidate.json that enforce it. The team wants four-space indentation, BEM classes, kebab-case ids and SRI on third-party scripts.
Show solution
{
"extends": ["html-validate:recommended", "html-validate:prettier"],
"rules": {
"attribute-boolean-style": ["error", { "style": "omit" }],
"id-pattern": ["error", { "pattern": "kebabcase" }],
"class-pattern": ["error", { "pattern": "bem" }],
"heading-level": "error",
"require-sri": ["error", { "target": "crossorigin" }]
}
}{
"printWidth": 100,
"tabWidth": 4,
"useTabs": false,
"endOfLine": "lf",
"htmlWhitespaceSensitivity": "css"
}root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = trueThe three files agree on four spaces and LF endings, so the editor, the formatter and the linter never disagree. Rules such as attribute order and meaningful alt text stay in the written standard with "Review" as their enforcer.
Quick Quiz
1. Why does the team config extend html-validate:prettier?
The formatter owns quotes, doctype case and void style, so the linter stops checking them.
2. A browser-based checker never reports <HTML> in capitals. Why?
Source-level rules need a tool that reads the raw text, such as Prettier.
3. Which comment follows the TODO policy?
A TODO must name an owner and a ticket so someone actually does it.
4. Which rule cannot be checked by Prettier or html-validate as configured here?
No rule reorders or checks attribute order, so it stays a review item.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
