Is It Bad Practice to Comment Out Single Lines of CSS with //

Is it bad practice to comment out single lines of CSS with //?

I don't know how future and/or exotic browsers will interpret non-official hacks like //, so I’d rather stick with the appropriate notation:

li {
float:left;
text-indent:0px;
/* list-style-type:none; */
}

How should you comment CSS?

I think there are generally two cases where comments should be used:

  1. If you are using hacks.
  2. To illustrate the page structure.

This may be beyond the question, but you should first ask: how to structure CSS?

With a proper structure, comments make it a breeze to navigate and locate the sections in your page, e.g.

/***************
* UI Elements *
***************/
h1, h2, h3, p {
...
}
table, form, input, textarea {
...
}

/* Custom Radio button hack: use background-image/position on label */
input[type=radio] {
display:none;
}
input[type=radio] + label {
background-image: url(...);
}
input[type=radio]:checked + label {
background-image: url(...);
}


/**********
* Header *
**********/
#site-header {
...
}
#logo {
...
}

/***********
* Sidebar *
***********/
#site-sidebar {
...
}
.item-in-sidebar {
...
}

/**********
* Footer *
**********/
#site-footer {
...
}

Anyone touching the CSS should have the confidence that editing something in, say, the header section won't affect anything else on the page. If a fundamental change in an element's style is required across all pages and sections, all you need to do is edit the relevant element in the UI Elements portion of CSS.

Needless to say, good CSS structure depends on your markup being well-written and cleanly separated from presentation. If your HTML is afflicted with div-itis, no amount of comments can help save your CSS.

Is it bad practice to leave commented-out code in production releases

Best practice is to use SCM. If you think the old code is really something people will want to refer to in the future, leave a comment of "// We used to do it another way, which had interesting property X -- see revision 103" rather than leaving whole chunks of code that don't do anything.

Commenting out code has its place, but that place is quickie tests that aren't even worth the time to do a branch.

If the code is worth keeping, it's worth more than being lost in a comment somewhere. If it is not worth keeping, kill it with fire.

(Comment out)/wrap multiple lines of CSS with inline and multi-line comments already present

You can put the unwanted code in a media type that doesn't exist.

@media DISABLED {
unwanted code here
}

Sort of unrelated:

In languages where // or -- can do a single-line comment, and editors that support this, I love keyboard shortcuts that do comments for you. In Visual Studio, for example, I can hit ctrl k, c and it will comment the selected text with single line comments. ctrl k, u just removes the // from the beginning of each selected line!

PHP: Is it bad practice to jump into PHP just to comment?

  1. There is no other way to hide comments from the HTML source code.
  2. Yes, it's more work for the PHP compiler but the delay will be minimal.
  3. I think the readability is certainly more important than few additional nanoseconds of executing time.

How reliable is 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 /* */.

What are the implications of using !important in CSS?

Yes, I'd say your example of using !important is bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.

What's wrong with !important:

Specificity is one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:

button { 
color: black;
}
button.highlight {
color: blue;
font-size: 1.5em;
}
button#buyNow {
color: green;
font-size: 2em;
}

On this page, all buttons are black. Except the buttons with the class "highlight", which are blue. Except that one unique button with the ID "buyNow", which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.

!important, however, is added at a property level, not a selector level. If, for instance, we used this rule:

button.highlight {
color: blue !important;
font-size: 1.5em;
}

then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the button#buyNow selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).

An element <button class="highlight" id="buyNow"> would have a font-size of 2em, but a color blue.

This means two things:

  1. The selector does not accurately convey the importance of all the rules inside it
  2. The only way to override the color blue is to use another !important declaration, for example in the button#buyNow selector.

This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One !important leads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one !important can be a useful short-term solution, it will come back to bite you in the ass in the long run.

When is it okay to use:

  • Overriding styles in a user stylesheet.

This is what !important was invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.

  • Overriding 3rd party code & inline styles.

Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use !important sparingly.

  • Utility classes

Many libraries and frameworks come with utility classes like .hidden, .error, or .clearfix. They serve a single purpose, and often apply very few, but very important, rules. (display: none for a .hidden class, for example). These should override whatever other styles are currently on the element, and definitely warrant an !important if you ask me.

Conclusion

Using the !important declaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.

There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.

Does HTML5 change the standard for HTML commenting?

There is no new standard for comments in HTML5. The only valid comment syntax is still <!-- -->. From section 8.1.6 of W3C HTML5:

Comments must start with the four character sequence U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS (<!--).

The <! syntax originates in SGML DTD markup, which is not part of HTML5. In HTML5, it is reserved for comments, CDATA sections, and the DOCTYPE declaration. Therefore whether this alternative is bad practice depends on whether you consider the use of (or worse, the dependence on) obsolete markup to be bad practice.

Validator.nu calls what you have a "Bogus comment." — which means that it's treated like a comment even though it's not a valid comment. This is presumably for backward compatibility with pre-HTML5, which was SGML-based, and had markup declarations that took the form <!FOO>, so I wouldn't call this new. The reason they're treated like comments is because SGML markup declarations were special declarations not meant to be rendered, but since they are meaningless in HTML5 (with the above exceptions), as far as the HTML5 DOM is concerned they are nothing more than comments.

The following steps within section 8.2.4 lead to this conclusion, which Chrome appears to be following to the letter:

  1. 8.2.4.1 Data state:

    Consume the next input character:

    "<" (U+003C)

    Switch to the tag open state.

  2. 8.2.4.8 Tag open state:

    Consume the next input character:

    "!" (U+0021)

    Switch to the markup declaration open state.

  3. 8.2.4.45 Markup declaration open state:

    If the next two characters are both "-" (U+002D) characters, consume those two characters, create a comment token whose data is the empty string, and switch to the comment start state.

    Otherwise, if the next seven characters are an ASCII case-insensitive match for the word "DOCTYPE", then consume those characters and switch to the DOCTYPE state.

    Otherwise, if there is an adjusted current node and it is not an element in the HTML namespace and the next seven characters are a case-sensitive match for the string "[CDATA[" (the five uppercase letters "CDATA" with a U+005B LEFT SQUARE BRACKET character before and after), then consume those characters and switch to the CDATA section state.

    Otherwise, this is a parse error. Switch to the bogus comment state. The next character that is consumed, if any, is the first character that will be in the comment.

    Notice that it says to switch to the comment start state only if the sequence of characters encountered is <!--, otherwise it's a bogus comment. This reflects what is stated in section 8.1.6 above.

  4. 8.2.4.44 Bogus comment state:

    Consume every character up to and including the first ">" (U+003E) character or the end of the file (EOF), whichever comes first. Emit a comment token whose data is the concatenation of all the characters starting from and including the character that caused the state machine to switch into the bogus comment state, up to and including the character immediately before the last consumed character (i.e. up to the character just before the U+003E or EOF character), but with any U+0000 NULL characters replaced by U+FFFD REPLACEMENT CHARACTER characters. (If the comment was started by the end of the file (EOF), the token is empty. Similarly, the token is empty if it was generated by the string "<!>".)

    In plain English, this turns <!div displayed> into <!--div displayed--> and <!/div> into <!--/div-->, exactly as described in the question.

On a final note, you can probably expect other HTML5-compliant parsers to behave the same as Chrome.



Related Topics



Leave a reply



Submit