Logo OnlineCBT
HTML Tutorial
HTML · LESSON 8

HTML Comments and Code Formatting

Write clean, readable, and maintainable HTML code using comments and proper indentation.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 30 Jul 2026

HTML Comments and Code Formatting

1. Understanding HTML Comments

As web projects scale from simple single-page layouts to complex multi-component web applications, code readability becomes a top priority. HTML Comments allow developers to leave explanatory notes, section markers, or documentation directly inside the source code.

Comments are strictly ignored by the browser parser. They are not rendered on the visible web page viewport and do not impact layout structure or visual styling.

Syntax of an HTML Comment

An HTML comment begins with <!-- and ends with -->. Anything placed inside these opening and closing delimiters is ignored by the browser engine.

<!-- This is a single-line HTML comment -->
<h1>Visible Heading</h1>

<!-- 
    This is a multi-line HTML comment.
    It can span across multiple lines to explain complex layout logic
    or leave developer notes for team members.
-->
<p>This paragraph is rendered visible on the screen.</p>
Hardcoded Output Result (Rendered View in White Box)

Visible Heading

This paragraph is rendered visible on the screen.

Security Alert - Comments are Public!

While comments do not render on the screen, they are sent to the user's browser in plain text. Anyone can right-click your web page and choose "View Page Source" to read your comments. Never put passwords, API keys, private server paths, or sensitive user data inside HTML comments!

2. Practical Use Cases for HTML Comments

Professional developers use comments systematically to maintain clean, self-documenting codebases across team environments.

1. Document Sectioning & Navigation Landmarks

In large HTML documents containing hundreds of lines of code, comments serve as clear visual boundaries between major semantic sections.

2. Explaining Complex Structural Workarounds

If you use a specific structural layout trick or accessibility fix, comments inform future developers why that code exists so they do not delete it accidentally during refactoring.

3. Temporarily Disabling Code During Debugging

When troubleshooting layout bugs or broken forms, you can "comment out" blocks of code to isolate the problem without deleting the markup entirely.

<!-- ==========================================================================
     MAIN NAVIGATION SECTION
     ========================================================================== -->
<nav>
    <a href="#home">Home</a> | 
    <a href="#about">About</a>
    
    <!-- Temporarily hiding search bar during backend maintenance -->
    <!-- <input type="search" placeholder="Search site..."> -->
</nav>
Hardcoded Output Result (Rendered View in White Box)

3. Code Formatting & Indentation Best Practices

Browser engines ignore extra white spaces, tabs, and new lines inside HTML source code. A completely unindented, single-line HTML document will render identically to a beautifully indented one. However, unformatted code is impossible for human developers to read, debug, or maintain.

Core Formatting Standards

Formatting Rule Bad Practice (Avoid) Good Practice (Follow)
Consistent Indentation No spacing or random space counts. Children unaligned with parents. Use 2 or 4 spaces per nested hierarchy level consistently.
Lowercase Tag Names <DIV><H1>TITLE</H1></DIV> <div><h1>Title</h1></div>
Quoted Attribute Values <input type=text class=box> <input type="text" class="box">
Closing All Elements Leaving container tags open (e.g. <p>Text 1 <p>Text 2). Explicitly close every container element (<p>Text 1</p>).

Nested Indentation Tree Mechanics

Whenever an element contains child elements, the child nodes must be indented one step to the right relative to the parent opening tag.

<!-- Properly Indented Parent-Child Structure -->
<article class="card">
    <header class="card-header">
        <h2>Clean Code Standard</h2>
    </header>
    <div class="card-body">
        <p>Notice how each child level shifts inward by 4 spaces.</p>
    </div>
</article>
Hardcoded Output Result (Rendered View in White Box)

Clean Code Standard

Notice how each child level shifts inward by 4 spaces.

4. Automated Code Formatting with Prettier

Manually hitting spacebars to align code is tedious and error-prone. Modern front-end engineering relies on automated code formatters like Prettier inside Visual Studio Code.

Setting Up Auto-Formatting on Save

  1. Open VS Code Settings by pressing Ctrl + , (Windows) or Cmd + , (macOS).
  2. Search for "Default Formatter" and set it to Prettier - Code Formatter.
  3. Search for "Format On Save" and check the toggle box.
Formatting Workflow Advantage:

With "Format On Save" enabled, you can write messy code rapidly without worrying about spacing. The moment you save the file (Ctrl + S / Cmd + S), Prettier automatically cleans indentation, fixes quotes, and structures tag alignment in milliseconds!

5. Homework Assignments & Practical Exercises

Task 1: Code Documentation Exercise (Current Lesson)

Open an existing HTML project file. Add multi-line header comments at the top containing project title, author name, and date. Add section divider comments separating the <header>, <main>, and <footer> sections.

Task 2: Refactoring Messy HTML (Current Lesson)

Take an intentionally messy, unindented HTML snippet containing mixed uppercase tags and missing quotes. Manually reformat it using 4-space nested indentation, lowercase tags, and quoted attribute values until it achieves a clean 100% W3C validation score.

Task 3: Full Workspace Formatting Revision (All-Inclusive Task)

Combine learnings from Lessons 01 through 08: Configure Prettier inside VS Code, open a complex multi-section page, verify that saving auto-formats your DOM structure, inspect the formatted elements in Chrome DevTools, and confirm that all comments remain invisible on the viewport.

6. Frequently Asked Interview Questions

Q1: Do HTML comments affect website page loading performance or file size?

Answer: In development environments, comments add a tiny amount of file size (measured in bytes). However, in modern production workflows, build tools and minifiers automatically strip out all HTML comments before deploying code to servers, ensuring zero impact on live performance.

Q2: What is the difference between commenting out code in HTML versus hiding it with CSS display: none?

Answer: Commenting out HTML (<!-- <div>...</div> -->) prevents the browser from building those nodes into the DOM tree entirely. Hiding code via CSS (display: none;) allows the browser to parse and construct the DOM nodes in memory, but suppresses visual rendering on the screen.

Q3: Why is consistent 2-space or 4-space code indentation considered critical in team environments?

Answer: Consistent indentation reveals parent-child-sibling relationships at a glance, making unclosed tags instantly visible. In collaborative Git workflows, consistent formatting prevents unnecessary diff conflicts caused by developers using different tab spacing styles.

Q4: Can you nest an HTML comment inside another HTML comment?

Answer: No, nesting HTML comments (e.g. <!-- outer <!-- inner --> outer -->) is invalid in HTML specifications. The first closing --> encountered by the parser terminates the entire comment block, causing the remaining text to render on the page as broken raw code.

Next Lesson: Headings and Paragraphs

Now that you master clean code formatting and document commenting, our next lesson explores textual content structure:

  • The Heading Scale (h1 to h6): Defining semantic document outlines and SEO heading hierarchy.
  • Paragraph Mechanics (p): Handling block text grouping, spacing, and word wrapping.
  • Line Breaks (br) vs. Horizontal Rules (hr): Knowing when to break lines vs. when to introduce thematic breaks.
  • Preformatted Text (pre): Preserving whitespace, tabs, and line breaks for code blocks and poetry.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat