CSS comments are used to add notes within your stylesheets, making your code more readable and understandable. They are ignored by the browser and do not affect the rendering of your web page.
Example 1: Single-line Comment
/* This is a single-line comment */
body {
background-color: lightblue; /* This comment explains the background color */
}
Explanation This example demonstrates a single-line comment using /* ... */
. It's useful for brief notes or explaining a single property.
Example 2: Multi-line Comment
/*
* This is a multi-line comment.
* It can span across multiple lines
* to provide more detailed explanations.
*/
h1 {
color: navy; /* Sets the heading text color */
}
Explanation This code showcases a multi-line comment, also enclosed within /* ... */
. This format is ideal for longer descriptions or block-level comments.
Example 3: Commenting Out Code
p {
font-size: 16px;
/* color: gray; /* This line is commented out and won't be applied */ */
}
Explanation Here, a CSS property color: gray;
is commented out. This technique is often used for debugging or temporarily disabling styles.
Example 4: Inline Comment
div {
width: 100px; /* Specifies the width */
height: 100px; /* Specifies the height */
}
Explanation This example shows inline comments placed on the same line as the CSS property. This is a compact way to explain individual declarations.
Example 5: Nested Comments (Avoid)
/*
This is an outer comment.
/* This is a nested comment - generally avoid this as it can break parsing */
*/
.container {
border: 1px solid black;
}
Explanation While some parsers might handle this, nesting CSS comments can lead to unexpected behavior and is generally discouraged. Stick to clear, non-nested comment structures for better maintainability.