How to Add Comments in CSS
Introduction
Adding comments in CSS is a fundamental practice that helps developers document their code, organize stylesheets, and make maintenance easier. Whether you are working on a small project or a large‑scale web application, comments serve as inline notes that explain why a particular rule exists, what alternatives were considered, and how different sections interact. This article will walk you through the syntax, types, and best practices for using comments effectively in CSS, ensuring your stylesheets remain clear and professional Most people skip this — try not to. That's the whole idea..
Not obvious, but once you see it — you'll see it everywhere.
Understanding CSS Comment Syntax
Basic Syntax
In CSS, comments are enclosed within /* and */. Anything placed between these delimiters is ignored by the browser and will not affect rendering. The simplest form looks like this:
/* This is a comment */
Multi‑line Comments
You can span multiple lines within a single comment block, which is useful for longer explanations:
/*
This comment covers several lines.
It can describe a whole section of styles.
*/
Single‑line Comments
If you only need a brief note on the same line as code, you can place the comment after the declaration:
p { color: red; } /* Red text for paragraphs */
Comments Inside Rules
Comments can be inserted anywhere a declaration is allowed, including inside a rule set, before a selector, or even after a property value:
/* Style for headings */
h1, h2, h3 {
font-family: *Georgia*; /* Use Georgia if available */
margin-top: 1rem; /* Space above headings */
}
Steps to Add Comments in CSS
-
Identify the Purpose
Before adding a comment, decide what information you need to convey:- Why a rule was written in a certain way.
- What the rule does for the layout or design.
- How the rule interacts with other rules.
-
Choose the Right Placement
- Before a selector to describe the group of elements.
- Inside a rule set to explain individual properties.
- Between sections of a stylesheet to separate logical groups.
-
Write Clear, Concise Text
Use short sentences and avoid jargon that could confuse future readers.
Example:/* Center the navigation bar horizontally */ nav { justify-content: center; } -
Keep Comments Updated
As you refactor code, update or remove outdated comments. Stale comments can mislead developers. -
Use Comments to Mark Regions
When a stylesheet becomes long, insert a comment that acts as a header for a section:/* ===================== Layout – Main Content ===================== */ .container { ... }
Types of CSS Comments
1. Descriptive Comments
These explain what the code does. They are the most common type and help teammates understand intent Small thing, real impact. Less friction, more output..
/* Header styling – applies to all elements */
header {
background-color: #333;
color: #fff;
padding: 1rem;
}
2. Temporal Comments
Used to note temporary solutions or work‑arounds that may be removed later It's one of those things that adds up..
/* TODO: Replace this hack with a proper flexbox layout */
.logo { float: left; }
3. Documentation Comments
Similar to Javadoc in JavaScript, these can be extracted by documentation tools. They often follow a specific format.
/**
* Navigational menu styling.
*
* @class .nav-menu
* @since 1.2.0
*/
.nav-menu { ... }
4. Debugging Comments
During development, you might comment out sections of CSS to isolate issues. This is different from regular comments because you temporarily disable code rather than just annotate it.
/*
Debug: The following rule was causing overflow on mobile.
Disabled until fix is implemented.
.sidebar { width: 100%; }
*/
Best Practices for CSS Comments
- Be Specific: Instead of “style here,” write “Apply dark theme to footer.”
- Avoid Redundancy: Do not comment on obvious properties; the code already shows
color: red;. - Limit Length: Keep comments short; long paragraphs are better placed in external documentation.
- Use Consistent Formatting: Stick to a single style (e.g., always start with a capital letter and end with a period).
- Separate Logical Sections: Use a pattern like
/* ==== SECTION NAME ==== */to visually break up the stylesheet. - Do Not Comment Out Large Blocks: If you need to disable a block, consider using a preprocessor or CSS comments inside a comment block, but avoid leaving massive commented sections that clutter the file.
How Comments Interact with CSS Preprocessors
If you use a preprocessor like SASS or LESS, the comment syntax differs:
- SASS supports both
/* … */(CSS‑style) and// …(single‑line) comments. - LESS also offers
/* … */and// ….
On the flip side, the fundamental rule remains the same: anything inside the delimiters is ignored by the compiled CSS output. When you compile SASS to plain CSS, the comments you wrote with // become regular /* … */ comments in the final file.
Frequently Asked Questions (FAQ)
Q1: Can I put a comment inside a property value?
A: No. CSS does not allow comments inside property values. Take this: color: /* red */; is invalid and will cause a parsing error
5. Maintaining Comment Quality Over Time
Comments are only as good as their upkeep. Day to day, in fast‑moving projects, stale comments can mislead more than help. Treat CSS comments like living documentation: review them during code refactors, and remove or update them when the associated code changes Not complicated — just consistent..
comments” that no longer reflect reality. Schedule a quarterly “comment audit” alongside your CSS linting pass: search for /* patterns, verify each block still describes the current implementation, and delete anything that has drifted. This small habit keeps the stylesheet readable and prevents future developers from chasing ghosts And that's really what it comes down to..
Conclusion
Well‑crafted CSS comments are the signposts that turn a sprawling stylesheet into a navigable map. Remember that preprocessors merely transform your comment syntax; the discipline of writing meaningful annotations remains entirely yours. By categorizing comments—section headers, component documentation, state explanations, and temporary debug notes—you give every reader (including your future self) instant context without clutter. Finally, treat comments as living artifacts: audit them regularly, purge the obsolete, and update the relevant. So naturally, follow the best‑practice checklist: be specific, avoid redundancy, keep length in check, enforce a consistent format, and separate logical areas with clear visual delimiters. When comments evolve alongside the code they describe, they become a reliable layer of documentation that accelerates onboarding, eases maintenance, and ultimately makes your CSS a pleasure to work with.
8. Automating Comment Hygiene
Keeping annotations current is a discipline that scales best when it is reinforced by tooling. Modern build pipelines can enforce comment standards automatically, reducing the manual audit burden No workaround needed..
Stylelint rule example
{
"rules": {
"comment-pattern": [
true,
{
"regex": /^\/\*\s*Section:\s*([A-Za-z0-9_-]+)\s*\*\//,
"message": "Section comments must follow the ‘Section: ’ format."
}
],
"no-orphaned-comments": true
}
}
The rule above flags any section header that does not adhere to the prescribed naming convention and disallows stray comments that are left behind after a feature is removed Worth keeping that in mind..
Preprocessor plugins
- SASS – the
sass-meaningful-commentsplugin warns when a comment block is empty or contains only whitespace. - Less –
less-orphaned-commentsdetects comments that reference code no longer present in the repository.
CI integration
Add a lint step in your CI configuration (e.g., GitHub Actions, GitLab CI) that runs stylelint or scss-lint. Fail the build if any comment violations are reported, ensuring that only clean, up‑to‑date documentation reaches production Nothing fancy..
By weaving these checks into the development workflow, teams transform comment maintenance from an optional afterthought into a mandatory part of every pull request That's the whole idea..
Final Thought
Treat CSS annotations as living documentation that evolves hand‑in‑hand with the codebase. When disciplined writing is paired with automated safeguards, the stylesheet remains navigable, understandable, and resilient to change—turning what could be a chaotic cascade of rules into a well‑orchestrated visual language It's one of those things that adds up. And it works..
You'll probably want to bookmark this section Worth keeping that in mind..