How Reliable Is Double-Slash Comment in CSS

How reliable is a double-slash comment in CSS?

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, it does not mention //

However, // are 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

Firefox Elements Panel

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

Chrome Elements Panel

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 Elements Panel

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

IE11 Elements Panel

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 /* */.

Is it bad practice to prefix single lines of CSS with // as a personal comment style?

I see that there were/are lots of people complaining about this and since this is an older question, there is probably a lot of people reading it wondering if it is still true, or if there is actually a standard in the first place. Allow me to clear the air. The following are the core reasons for the strict CSS comment policy:

#1 It is not standard

Standardized at least since CSS 2.1, comments are to ONLY be encased in /* and */. While some browsers tolerate //, they aren't supposed to, and are only one inch from someone saying "oh yeah that's non-standard" or "hey! That's non-standard, fix it!"; and then guess what, your CSS code, which WAS working, now doesn't for thousands of people (and may have already not been working for hundreds of others). I will add that <!-- and --> are allowed but only (and I mean ONLY) when they appear within an HTML document, not in a .css source file. If your browser is so old that it can't skip over <style> tags, it's probably time for a new browser 10 years ago. Even Lynx and other text browsers know not to read them, so commenting it out is only useful in very isolated situation where hardware and software are landlocked in their current working state.

#2 It is not (very) cross-platform friendly

The single line comment, which starts anywhere on a line with //, is terminated by 'newline' which is/are not a cross-platform standardized character(s). Worse, some might have one character for a newline, or 2... and when these platforms mix together, a newline could be lost, and there goes your terminator...and some or all of your code is now being commented out that was not supposed to be, you don't have to be a genius to know what the consequences of that might be, especially if you control features of your site solely through CSS which many do.

#3 The Standard IS Friendly and Uniform to All

The /* and */ delimiters are ALWAYS going to be the same characters on EVERY computer regardless of architecture, operating system, etc.

#4 Newlines are Whitespaces

The last reason (yes, there is one more), newline character(s) are considered (in CSS and many other languages) to be whitespace, and */ is not whitespace is it? And if you think about it at this point, it should be pretty clear you should NOT be using a whitespace to terminate a comment especially since whitespace is and can be stripped by many HTML/CSS parsers, or reformatted without you even knowing about it.

#5 CSS != C/C++

Now if you are about to fly out of your seat and yell at me about "Hey, but C++...", remember those compilers and IDEs have tons of newline checking and detection built into them so they can take it. Most compilers do not reformat your code unless asked, and many IDEs will usually ask you what kind of newlines your document is using if it can't guess on its own. If we did this with CSS pages for the end user every time one was loaded, imagine the nightmare it would be trying to get around. Furthermore, C/C++ code is not parsed at run-time and is compiled, so then much of the time, the user never gets the document in question in the first place. The source files are not being constantly viewed by the entire world on hundreds of platforms and many operating systems, and a million different browsers either. The comments are stripped out before they ever get to the end user. CSS source comes right to the user's browser and has to be very resilient not knowing what is on the other side, so the caveat is that it must be ready for anything the end user has or does, not anything the developer does or has!

#6 It's inconvenient

No, it is very annoying having to type that extra */, but the blame for this mainly goes to developers of CSS editing software who don't offer auto completion. If you use a specialized editor that can do that, preferably out of the box, then you'll find it is just as easy as using //. Get in the habit of typing /**/ and then backspace 2, it will help you to not forget and makes it a little easier. Better still, you can set up a hot key to just lay down those for you. Windows and Linux both have powerful tools to allow this (KDE is very good for that).


I hope this helps everyone understand the "why" behind the "how", and remember just because something works for you, doesn't mean it is the standard, and to sum up:

YES, IT IS BAD PRACTICE to use it, just say NO to the double slash!!!
If you need a visual aid to remind you of this important fact, just burn this image into your mind (thanks to those of you who have nothing better to do but make pictures like this):

No double slash


PS: If you really want something to complain to the ones making/breaking CSS standards (W3C, elbow), someone starts a discussion about how unnecessarily long and wrong the "!important" keyword is! But that is not part of this question so I won't go into it.

References

  • W3C: CSS 2.1 working draft: comment characters.
  • W3C: CSS syntax module level 3: railroad diagrams of parser-to-character interpretations.
  • Stack Overflow: Various Stack Overflow articles with practically the same subject as this one.
  • w3schools: CSS 3 syntax standard (which in turn references W3C).
  • sitepoint: CSS syntax annotation on "not using double-slash".
  • mozilla|mdn: relaxed CSS 3 processing allows double slash in input files.

Is there any downside for using a leading double slash to inherit the protocol in a URL? i.e. src=//domain.example

If the browser supports RFC 1808 Section 4, RFC 2396 Section 5.2, or RFC 3986 Section 5.2, then it will indeed use the page URL's scheme for references that begin with "//".

Do double forward slashes direct IE to use specific css?

// is not a valid CSS comment.

Browsers that parse CSS properly will ignore //position because //position is not a valid property name (details are here, property -> IDENT S* -> follow it through).

This only works in IE7 due to its well known bug of accepting properties with junk prepended to them.

It's not just // that works. IE7 will have red text here:

body {
!/!*//color: red;
}

This is most typically exploited with *, for example *display: inline; as part of the display: inline-block workaround for IE7.

Two forward slashes in a url/src/href attribute

The "two forward slashes" are a common shorthand for "request the referenced resource using whatever protocol is being used to load the current page".

Best known as "protocol relative URLs", they are particularly useful when elements — such as the JS file in your example — could be served and/or requested from either a http or a https context. By using protocol relative URLs, you can avoid implementing

if (window.location.protocol === 'http:') {
myResourceUrl = 'http://example.com/my-resource.js';
} else {
myResourceUrl = 'https://example.com/my-resource.js';
}

type of logic all over your codebase (assuming, of course, that the server at example.com is able to serve content through both http and https).

A prominent real-world example is the Magento 1.X E-Commerce engine: for performance reasons, the category and product pages use plain http by default, whereas the checkout is https enabled.

If some resources (e.g. promotional banners in the site's header) are referenced via non protocol relative URLs (i.e. http://example.com/banner.jpg), customers reaching the https enabled checkout are greeted with a rather unfriendly

"there are insecure elements on this page"

prompt - which, one can safely assume, isn't exactly great for business.

If the aforementioned resource is referenced via //example.com/banner.jpg though, the browser takes care of loading it via the proper protocol both on the plain http product/category pages and in the https-enabled checkout flow.

tl;dr: With even the slightest possibility of a mixed http/https environment, just use the double slash/protocol relative URLs to reference resources — assuming that the host serving them supports both http and https.

stylelint-scss - Is there a way to disable double-slash-comments?

The no-invalid-double-slash-comments rule disallows a particular type on double slash comment in CSS. Quoting from the docs:

If you are using a preprocessor that allows // single-line comments (e.g. Sass, Less, Stylus), this rule will not complain about those. They are compiled into standard CSS comments by your preprocessor, so stylelint will consider them valid.

I don't believe there's an existing rule to disallow SCSS double-slash comments. However, you can write a simple plugin to do this. I suggest you use the comment-no-loud rule from the stylelint-scss plugin pack as a blueprint.

How do I customize comment characters in VS Code?

VSCode is behaving correctly in this case. Both /* ... */ and // ... are valid comments in LESS, they do however differ slightly in the generated CSS:

  • /* ... */ will compile to /* ... */
  • // ... will be removed during compilation

This allows comments to be removed, saving extra bytes from being transferred to the client. The double-slash style comment is typically what LESS developers use for that reason.



Related Topics



Leave a reply



Submit