CodeBlanks Logo Icon CodeBlanks

Comments and whitespace

CSS course · Beginner · Lesson 4/82

Learn CSS comments and how to write readable code with indentation.

CSS comments

In CSS, comments are written as /* ... */. Between the opening and closing marks you can put any text; the browser ignores it.

Comments leave explanatory notes in the code: 'this block styles the heading', 'this part is temporary' and so on. A comment at the top of a file says what the file is for. Your teammates — and your future self — will thank you.

Indentation and readability

CSS does not care about whitespace; the browser ignores extra spaces and line breaks. But to the human eye, indented code is far easier to read.

A common practice: put each declaration on its own line, indented by two spaces. Align the curly braces to the same column. That makes it clear where one block ends and the next begins.

Exercise Write a comment and an indented h2 block

Put a /* Heading style */ comment on top, and an h2 block below it. Inside the block, add a color: maroon declaration. Indent the declaration so the code reads nicely.

Show example solution
/* Heading style */
h2 {
  color: maroon;
}

Test yourself

  1. What are CSS comments for?

    /* body block: default text color */
    body {
      color: #222;
    }
    • Compress code to shrink the file size
    • Tell the browser which CSS version to use
    • Add an external link to the HTML document
    • Leave notes in the code; the browser ignores them
    Show answer

    Leave notes in the code; the browser ignores them — Correct. Comments leave notes in the code; the browser skips them.

  2. Close the CSS comment

    /* body block ____
    body {
      color: #222;
    }
    Show answer
    /* body block */
    body {
      color: #222;
    }
  3. Match each mark to its meaning

    /* ... */
    CSS comment
    { }
    wraps declarations
    ;
    declaration separator
    Two spaces
    common indent

All lessons in Beginner