Key Takeaways
- HTML comments are ignored by browsers; use to add notes, label sections, and aid debugging without affecting the page.
- Follow strict syntax: avoid “–” inside content, don’t end content with a hyphen before –>, and never nest comments (HTML doesn’t support nested comments).
- Use comments to mark regions (START/END), TODOs, and build or version info; view/edit them in DevTools or generate via JavaScript document.createComment().
- Keep comments concise, relevant, and free of sensitive data; strip debug notes in production with tools like html-minifier-terser for better performance.
- Use proper comment styles per context: HTML for markup, // or /* / in scripts, and / */ in CSS; legacy IE conditional comments apply only to IE 5–9.
- Validate and format with tools (Nu HTML Checker, HTMLHint, Prettier) to maintain safe, consistent HTML comment usage aligned with WHATWG and MDN.
Writing HTML can get messy fast. I use comments to stay organized and to leave myself quick notes. Browsers ignore them so they never show on the page. That means I can explain sections or mark to do items without breaking anything.
In this guide I’ll show the basics of HTML comments and when to use them. You’ll see how a simple note like <!-- Navigation starts here -->
can save time later. I’ll keep it simple and friendly so you can start right away.
What Are HTML Comments?
HTML comments are non rendered notes in markup.
Syntax
<!-- This is a single-line comment -->
<!--
This is a multi-line comment
Spanning several lines -->
<!-- Temporarily hide markup
<div class="card">...</div> -->
Purpose
- Use comment html markers to explain structure for teammates, designers and future me
- Use html comment syntax to isolate blocks during debugging in Chrome, Firefox and Safari
- Use html comments to label sections for templates, components and partials
Behavior
- Use comments to add context in source view, not presentation in the viewport
- Use comments to create Comment nodes in the DOM tree, not visible elements in layout
- Use comments to store notes for build tools like linters and bundlers, not runtime features
Constraints
- Use exactly, if the content contains — the parser flags a parse error per WHATWG HTML
- Use plain text inside, if the text ends with – before > the closer breaks per WHATWG HTML
- Use one level only, if nesting appears the browser treats inner markers as text
Access
- Use DevTools Elements to view and edit comment nodes in place
- Use JavaScript document.createComment to generate comments dynamically
- Use server templates to inject comments for environments like SSR and static builds
Standards and compatibility
- Use the WHATWG HTML definition for exact parsing rules, see https://html.spec.whatwg.org
- Use MDN for examples and DOM APIs, see https://developer.mozilla.org/docs/Web/HTML/Comment_tags
- Use conditional comments only in legacy IE, see IE 5 to IE 9 docs on MDN
Item | Numeric value | Note |
---|---|---|
Closing marker hyphens | 2 | Comment closes with –> per WHATWG HTML |
Disallowed sequence in content | 2 | The sequence — is not allowed inside content per WHATWG HTML |
Supported nesting levels | 0 | HTML does not support nested comments per WHATWG HTML |
DOM Comment nodeType | 8 | Node.COMMENT_NODE equals 8 per MDN |
Legacy IE conditional support versions | 5–9 | Conditional comments parsed in IE 5 to IE 9 per MDN |
Syntax: How To Comment In HTML
I explain the exact HTML comment syntax and its safe patterns. I keep the format tight to match the spec.
Basic Comment Syntax
Use the standard syntax for any HTML comment.
<!-- This is a comment -->
<p>Visible text</p>
Follow these rules when I write comment text.
- Use as the only delimiters
- Avoid two consecutive hyphens inside, for example —
- Keep the final character before –> not a hyphen
- Place comments outside text nodes and inside the HTML document tree
Examples for common placements.
<!-- Header start -->
<header>...</header>
<!-- Header end -->
<p>Price <!-- currency USD --> $25</p>
Key syntax limits in numbers.
Rule | Numeric detail |
---|---|
Disallowed hyphen run | 2 consecutive hyphens inside content |
Disallowed trailing hyphen | 1 hyphen before –> |
Sources: WHATWG HTML Living Standard section 8.1.6, MDN Web Docs HTML comments.
Commenting Out Blocks
Use comments to hide blocks of markup during testing.
<!--
<section class="promo">
<h2>Promo</h2>
<p>Save 20%</p>
</section> -->
Apply block comments with these constraints.
- Keep tags balanced inside the comment block
- Avoid nesting comment delimiters inside the block
- Prefer semantic labels at the block ends, for example
Practical Use Cases
I use HTML comment patterns to speed up navigation and teamwork. These focused use cases keep markup readable during edits.
Section Labels And TODOs
I label sections with HTML comments to mark boundaries and track tasks.
- Add start and end markers for large sections, if the block spans 50+ lines.
<!-- section: hero start -->
<section id="hero">...</section>
<!-- section: hero end -->
- Add hierarchical tags for nested regions, if the page holds 3+ major sections.
<!-- region: header -->
<!-- region: main -->
<!-- region: footer -->
- Add TODO markers with owners and dates for follow up, if the task ties to an issue tracker.
<!-- TODO[UX-1423][owner:@mia][2025-08-20]: refine CTA copy -->
- Add version or build info for quick audits, if the template compiles from multiple sources.
<!-- build: 2025-08-20 13:45 UTC, rev: a1c9f72 -->
- Add anchors for CMS snippets for stable includes, if editors swap partials often.
<!-- include: article-teaser -->
References: WHATWG HTML parsing rules, MDN HTML comments.
Debugging And Temporarily Disabling Markup
I comment out HTML to isolate bugs without deleting code.
- Wrap a suspect block with comment tags for fast A B checks, if the component breaks layout.
<!-- debug off
<div class="promo">...</div>
debug off -->
- Wrap script or style tags in HTML comments only in legacy contexts, if targeting very old IE quirk modes.
<!--
<script src="/legacy.js"></script> -->
- Wrap ARIA heavy widgets during tests with a visible placeholder, if assistive tech testing runs in parallel.
<!-- temp off: accordion -->
<div role="note">Accordion disabled during test</div>
Scenario | Lines commented | Time saved per run |
---|---|---|
Layout isolate header | 30 | 2 min |
Swap hero variant | 45 | 3 min |
Remove third party widget | 20 | 1 min |
References: WHATWG HTML, MDN script loading.
Collaboration Notes
I use concise HTML comment notes to align teams across reviews.
- Prefix notes with tags for quick scanning, if multiple roles touch the template.
<!-- NOTE[design]: spacing uses 8px scale -->
<!-- NOTE[seo]: keep h1 unique per URL -->
- Tag owners with handles and ticket IDs for traceability, if your team tracks status in Jira or GitHub.
<!-- REF[JIRA-572][@leo]: pending copy -->
- Link to design specs or audits for context, if the change impacts accessibility or SEO.
<!-- spec: https://www.w3.org/WAI/ARIA/apg/patterns/accordion/ -->
- Keep sensitive data out of comments for security, if the repo is public or logs source. See OWASP ASVS 1.2.
- Strip debug comments in production builds for lean HTML, if Lighthouse flags excessive bytes.
References: MDN HTML comments, WHATWG HTML, W3C WAI-ARIA APG, OWASP ASVS.
Best Practices And Style
Best practices for how to comment in HTML focus on clarity, safety, and maintainability. I keep a consistent HTML comment style across files and teams.
Keep It Concise And Useful
Write concise comments that describe intent, not mechanics. I keep HTML comments short and scan friendly.
- Use one sentence that states why the code exists, if more context lives in a ticket or doc.
- Place the comment above the related markup, if proximity avoids scrolling.
- Prefer domain terms over abstractions, if the project has a glossary.
- Replace vague words with specifics, if the feature has names and IDs.
- Mark section boundaries with paired comments, if a template spans many lines.
- Remove stale notes during edits, if the code no longer matches the message.
- Link to an issue or spec when relevant, if the rationale needs traceability.
- Keep examples brief and real, for example feature flags, A/B buckets, release IDs.
- Use TODO and FIX tags sparingly, for example TODO: aria labels, FIX: nav focus trap.
- Follow parsing limits from the HTML spec for validity, see WHATWG HTML parsing rules [https://html.spec.whatwg.org/multipage/syntax.html#comments].
Example:
<!-- START: product-card grid v3 A/B bucket B -->
<section class="product-card">...</section>
<!-- END: product-card grid v3 -->
Avoid Sensitive Information
Protect users and systems when I comment in HTML.
- Avoid secrets in source, for example API keys, tokens, session IDs.
- Avoid private data in notes, for example emails, addresses, phone numbers.
- Avoid internal paths, for example server hosts, database names, internal URLs.
- Avoid security hints, for example stack traces, framework versions, debug flags.
- Strip debug comments in production builds, if the pipeline supports minification.
- Audit comments before release, if the repository is public.
- Follow OWASP guidance on sensitive data exposure, see OWASP ASVS 4.0.3 V2 and V9 [https://owasp.org/www-project-application-security-verification-standard/].
Formatting Conventions
Keep formatting consistent so teams read comments fast in source view.
- Use uppercase markers for blocks, for example START, END, TODO.
- Use kebab case for identifiers, for example product-card, site-header.
- Use 1 space inside delimiters, for example not .
- Use 80 to 100 characters per line, if the team enforces width limits.
- Use paired tags for regions, for example and .
- Use stable anchors for diffs, for example with dates for audits.
- Use ASCII characters only, if cross locale tooling breaks on Unicode.
- Use MDN syntax guidance for correctness, see MDN HTML comments [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/comment].
Common Pitfalls And Edge Cases
Common pitfalls and edge cases crop up when I comment in HTML. I use these checks to avoid parser traps and broken behavior.
Nested Comments Limitation
HTML comments don’t nest. I keep 0 nested blocks to prevent parse errors per the HTML Standard (WHATWG HTML section “Comments”).
- Avoid double openers. I never place <!– inside an open block.
- Avoid stray closers. I never place –> inside comment text unless it ends the comment.
- Prefer block isolation. I close the first comment, then I open a new one for the next section.
Numbers that affect parsing:
Rule | Value | Source |
---|---|---|
Supported nesting depth | 0 | WHATWG HTML |
Prohibited hyphen run inside text | 2 consecutive hyphens “–” | WHATWG HTML |
Required closing sequence | “–>” exactly once at the end | WHATWG HTML |
Examples:
- Bad nesting example: <!– Outer Outer –>
- Safe split example:
Comments In Script And Style Tags
HTML comment markers interact with embedded languages. I follow language rules, not just HTML rules.
- Use JS comments in scripts. I use // or /* */ in
- Script legacy example:
- Style safe example:
Minification And Production Builds
Build pipelines often strip comments. I control what stays, and I strip what hurts performance.
- Remove HTML debug notes. I drop and in production to reduce bytes, if I retain documentation in source control. Tools: html-minifier-terser, vite, webpack plugins.
- Preserve license markers. I keep /*! … */ in CSS and JS when licenses require attribution, if I configure the minifier preserve pattern. Sources: terser “comments” option, CSSOM.
- Keep critical SSI or templating hints. I retain for SSI and for Knockout only when the server or client processor reads them. Sources: Apache SSI, Knockout docs.
- Guard analytics beacons. I avoid hiding scripts behind comments, if I rely on minifiers, since tools can reorder or collapse whitespace.
- HTML removal pattern: …
- JS license keep example: /*! MyLib v1.2 MIT */
- Tool config hint example: terser options { comments: /^!/ }
Tools And Workflow Tips
I speed up how to comment in HTML with editor automation and quality gates. I keep comments consistent across teams with shared configs.
Editor Shortcuts And Snippets
I insert and toggle HTML comments fast with built-in editor shortcuts.
Editor | Action | Shortcut | Source |
---|---|---|---|
VS Code | Toggle line comment | Ctrl+/ Windows Linux, Cmd+/ macOS | https://code.visualstudio.com/docs/editor/codebasics#_toggle-line-comment |
VS Code | Block selection box for multi-cursor | Shift+Alt+Drag Windows Linux, Option+Cmd+Drag macOS | https://code.visualstudio.com/docs/editor/codebasics#_multiple-selections-multicursor |
WebStorm | Toggle comment | Ctrl+/ Windows Linux, Cmd+/ macOS | https://www.jetbrains.com/help/webstorm/working-with-source-code.html#comments |
Sublime Text | Toggle comment | Ctrl+/ Windows Linux, Cmd+/ macOS | https://www.sublimetext.com/docs/editing.html#comments |
Vim | Toggle comment via commentary | gc with vim-commentary | https://github.com/tpope/vim-commentary |
- Use custom snippets for HTML comments, if I repeat section markers.
- Use this snippet pattern for start and end tags, if I bracket large regions.
- Use multi-cursor edits to stamp identical notes, if a template repeats blocks.
- Use Emmet to wrap selections with comments, if Emmet is active in the editor.
Example snippet body:
<!-- section: ${1:header} -->
${0}
<!-- /section: ${1:header} -->
Example Emmet wrap:
<!-- todo: ${1:explain} -->
|
<!-- /todo -->
Docs: Emmet wrap with abbreviation https://docs.emmet.io/actions/wrap
Linting And Prettifying
I enforce safe HTML comment syntax with linters and formatters.
Tool | Setting | Purpose | Source |
---|---|---|---|
HTMLHint | attr-lowercase true, tag-pair true | Catch malformed markup around comments | https://htmlhint.com/docs/user-guide/list-rules |
Nu HTML Checker | n/a | Validate HTML comment placement against the HTML Standard | https://validator.w3.org/nu |
Prettier | parser html, proseWrap preserve | Keep HTML comments intact and consistently spaced | https://prettier.io/docs/en/options.html#html |
html-minifier-terser | removeComments true, minifyJS true, minifyCSS true | Strip debug comments in production safely | https://github.com/terser/html-minifier-terser |
- Use HTMLHint to flag forbidden sequences in comments, if teammates edit raw markup.
- Use the Nu HTML Checker to spot spec violations, if I maintain legacy templates that mix script and style tags in HTML. Spec: HTML comments parsing https://html.spec.whatwg.org
- Use Prettier to normalize spacing around , if the repo standardizes formatting.
- Use html-minifier-terser removeComments true for builds, if comments carry no legal or license text.
- Use CI to run validators on pull requests, if the team relies on reviews for consistency.
Conclusion
Thoughtful comments are a tiny effort with a big payoff. They help my future self and my team move faster and with confidence. I treat them like any other part of the codebase. Clear. Consistent. Easy to trust.
My next move is simple. I pick one project and give its comments a quick health check. I add brief intent notes where they matter most. I cut anything stale or noisy. I adopt a small house style and stick to it.
I also make the habit durable. I add a review step for comments. I wire up editor help and basic checks. Ship clean today and save time tomorrow.
Frequently Asked Questions
What are HTML comments?
HTML comments are notes inside your markup that browsers ignore. They help you explain sections of code, mark TODOs, or label templates without affecting rendering. They’re visible in View Source and DevTools but not on the page.
Why should I use HTML comments?
Use comments to clarify intent, label sections, aid debugging, and align teammates. Clear notes reduce onboarding time, speed up reviews, and make refactors safer. They also help during audits by recording version or build info.
What is the correct syntax for HTML comments?
Wrap comments with . Example: . Avoid consecutive hyphens (–) inside the comment text and don’t nest comments. Place comments above the related markup for clarity.
Can HTML comments be multi-line?
Yes. Put your text between across multiple lines. Example:
Just avoid — inside the content and ensure one matching closer.
Do browsers render HTML comments?
No. Browsers ignore them during rendering, but they remain in the HTML source and DOM as comment nodes. Anyone can see them via View Source or DevTools.
Are HTML comments part of the DOM?
Yes. Comments exist as Comment nodes in the DOM. You can inspect them in DevTools and access them in JavaScript via Node.COMMENT_NODE or childNodes, though they don’t affect layout.
Can I nest HTML comments?
No. HTML comments cannot be nested per the WHATWG HTML spec. Closing the outer comment ends the entire comment block; inner comment markers are treated as text and may break parsing.
What are common HTML comment mistakes to avoid?
- Using — inside comments
- Double openers (<!– )
- Nesting comments
- Leaving sensitive data or credentials
- Misplacing comments inside script/style blocks without following language rules
How do HTML comments interact with JavaScript and CSS?
Inside