Comments are a vital part of writing clean, professional code. They allow you to leave notes for yourself or other developers explaining why a certain style was added. Browsers completely ignore comments, so they do not affect the layout or performance of your website.
CSS Comment Syntax
A CSS comment begins with /* and ends with */. Anything placed inside these markers will not be rendered by the browser.
The Syntax:
/* This is a CSS comment */
p {
color: red;
}
Single-line vs. Multi-line Comments
You can use comments for a single line of information or to explain a complex block of code over multiple lines.
Single-line:
h1 {
color: blue; /* Sets the heading color to blue */
}
Multi-line:
/* The following styles are specifically
designed for the main navigation bar
on the homepage.
*/
.navbar {
height: 60px;
background-color: #333;
}
Using Comments for “Commenting Out” Code
If you are testing different designs and want to temporarily disable a style without deleting it, you can “comment it out.”
div {
width: 100%;
/* background-color: green; */
background-color: blue; /* We switched to blue for testing */
}
Organizing Your Stylesheet
In large projects, comments are used to create “sections” in your CSS file, making it much easier to navigate.
/* =========================================
HEADER STYLES
========================================= */
header { ... }
/* =========================================
FOOTER STYLES
========================================= */
footer { ... }