Skip to main content

CSS Introduction

CSS Comments

Written by Updated CSS Comments exercises

Use CSS comments to document intent, explain unusual constraints, organize stylesheets, and temporarily isolate declarations while debugging.

A CSS comment is a note in your stylesheet that the browser ignores. It starts with /* and ends with */. It is also the quickest way to switch a rule off for a moment while you test something.

The syntax is the same for one line or many. Where comments fit into a stylesheet is part of CSS Syntax; how to keep a large stylesheet organized is covered in CSS Architecture.

Syntax

CSS Comments Syntax

css

/* This is a CSS comment */

CSS Comment Example

css

p {
    color: blue; /* This sets text color to blue */
}

A comment can sit on its own line or at the end of a declaration.

A comment over several lines, and a rule switched off

css

/*
  Card component
  Used on the home page and the blog list.
*/
.card { padding: 1rem; }

/* .card { border: 2px solid red; } */

The last rule is "commented out": it stays in the file but has no effect.

Comment decisions, not visible syntax

Useful comments explain a browser workaround, a layout constraint, a token source, or why an apparently simpler declaration is unsafe. Avoid comments that merely repeat the property name. CSS comments cannot be nested, so temporarily commenting out a region that already contains comments can end the comment earlier than expected; disable individual declarations or use version control instead.

Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Comments Example</title>
    <style>
        /* This is a comment for body styling */
        body {
            background-color: lightgray;
        }

        h1 {
            color: blue; /* Heading color */
        }

        /* Paragraph styling */
        p {
            color: green;
            font-size: 18px;
        }
    </style>
</head>
<body>

    <h1>CSS Comments</h1>
    <p>This paragraph is styled using CSS with comments.</p>

</body>
</html>

The page is styled exactly as if the comments were not there: a grey background, a blue heading and a green paragraph.

Browser Support

Feature
Chrome
Edge
Firefox
Safari
CSS comments11211

Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.

Mistakes to avoid

  • Using //. That is a JavaScript comment. In CSS, // note breaks the next rule.
  • Nesting comments. /* outer /* inner */ outer */ ends at the first */, and the rest becomes broken CSS.
  • Leaving private notes. CSS files are public; anyone can read your comments.

CSS Comments exercises

Switch a rule off

Write the rule .price { color: green; }, and also the rule .old { color: red; } but as a comment, so that it does nothing.

The HTML your code works on
<h1>Menu</h1>
<p class="price">$5</p>
<p class="old">$8</p>

Result

Check your answer to see it here.