Issue
How reliable is using a double-slash (//
) for a single-line comment in CSS? Are they part of the CSS specification? Do most mainstream browsers or CSS interpreters support them?
Solution
Comments using double slashes //
are invalid in CSS. The CSS spec states only the following about comments:
4.3.2. Consume comments
This section describes how to consume comments from a stream of code points. It returns nothing.
If the next two input code point are U+002F SOLIDUS (/) followed by a U+002A ASTERISK (*), consume them and all following code points up to and including the first U+002A ASTERISK (*) followed by a U+002F SOLIDUS (/), or up to an EOF code point. Return to the start of this step.
If the preceding paragraph ended by consuming an EOF code point, this is a parse error.
Return nothing.
In other words, only /* */
are valid comments. The spec does not mention //
.
However, //
is valid in certain CSS processors such as Less and SASS.
Per your comment:
...can you rely on browsers to understand that's a comment
No, the browser will attempt to interpret the syntax anyway and likely fail the rule based on it being a syntax error rather than it being a comment. The result will likely fail based on browser, but using it brings you into undefined behavior.
Browser Behavior with Double Slash Comments
Here are the results of the following rules being applied in different browsers. One styling uses the double slash at the beginning of the property, and one has the //
right before the value.
#some {
width: 500px;
/*height: 400px;*/
//color: blue;
background-color: //red;
}
Firefox
In Firefox ESR 52.9.0, you get a little yellow warning triangle next to color
and background-color
because //color
is an invald CSS property and because //red
is an invalid background-color
value.
Chrome
Interestingly, in Chrome 68.0.3440.106, I don't even see the //color: blue
show up in the elements panel which might mean that Chrome tries to consider the line a comment, but since //
being comments is not in the spec, you should not rely on it. However, background-color
also has the warning since //red
is an invalid value.
Safari
Safari 11.1.2 has the same behavior as Chrome where the //
led property is not even listed and the //
led value is a syntax error.
Internet Explorer 11
Internet Explorer 11.0.9600.19080 considers the entirety of //color: blue
to be the rule property and believes it has no value as though you had written //color: blue: ;
. It also lists background-color: //red
but considers it an error and does not apply it.
It should also be noted that for the following:
#some {
// width: 400px;
/* height: 400px; */
}
Most of the browsers will at least acknowledge the /* */
property and allow you to toggle it in the Dev tools. For Chrome and Safari, the //
led rule isn't even listed meaning you can't toggle it as you could with the /* */
.
Answered By - zero298
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.