? CSS Comments
⚡ Quick Overview
Comments in CSS are used to explain the code, improve readability, and temporarily disable parts of the styling code without deleting it. They are ignored by browsers and do not affect the final output on the web page.
? Key Concepts
- Explain code: Help yourself and other developers quickly understand what a style is doing.
- Improve readability: Break long stylesheets into clearly labeled sections.
- Debug safely: Comment out rules while testing instead of deleting them.
- No visual impact: Browsers completely ignore comments when rendering the page.
? Syntax of CSS Comments
CSS uses the same syntax for single-line and multi-line comments:
? View Code Example
Note: CSS comments must be enclosed within /* and */ and cannot be nested.
? Practical Example
Here is a practical CSS example using comments to explain each section:
? View Code Example
body {
background-color: #f0f0f0;
}
h1 {
color: darkblue;
text-align: center;
}
.hidden {
display: none;
}
? Live Output / Explanation
If you apply the above CSS to the HTML below, this is what happens:
? View Code Example
<h1>This heading is styled with CSS.</h1>
<p>This paragraph is visible.</p>
<p class="hidden">You should not see this text.</p>
The page background becomes light grey, the heading appears dark blue and centered, and the paragraph with class hidden is not visible because the CSS rule sets display: none.
? Why Use Comments in CSS?
- Clarify complex code: Comments help others (and future you) understand non-obvious styles.
- Debugging: Temporarily disable sections of CSS without deleting them.
- Organize styles: Group related rules such as layout, typography, and colors.
- Team collaboration: Make large stylesheets easier to work with in a team.
? Tips & Best Practices
- Use comments generously on large projects, especially around complex selectors.
- Always use proper CSS comment syntax:
/* comment */.
- Label sections with comments like
/* Header */, /* Footer */, or /* Buttons */.
- Update or remove comments when you change the related CSS, so they don’t become misleading.
- Do not put sensitive information in comments — they are still visible in the page source.
? Try It Yourself
- Take an existing CSS file and add comments to explain each major section (layout, typography, colors, etc.).
- Comment out one or two rules and reload the page to see how the design changes, then uncomment them again.
- Create a small CSS file from scratch and use comments to label the header, main content, and footer styles.
- Find a complex selector you wrote earlier and add a short comment explaining why you used that approach.