Chapter 3. Writing Better CSS

“Best practices” is a contentious term when it comes to writing CSS because there are so many different ways to accomplish the same thing, and the preference for one technique over another can be very subjective. However, as Chapter 1 explained, a good architecture is predictable, maintainable, extensible, and promotes code reuse. The ideas presented in the following sections keep this definition in mind and are intended to provide a solid foundation from which you can write better CSS.

Use Comments

Comments provide documentation that is helpful when looking at a file in the future. Comments should be used to document things including:

  • File contents

  • Selectors’ dependencies, usages, etc.

  • Why certain declarations were used (this is especially helpful in regard to browser quirks)

  • Deprecated styles that are being refactored and should no longer be used

CSS only has block-level comments (comments that can span multiple lines), and they begin with /* and end with */. In the event that a comment only needs one line, that can be done, but it must still begin with /* and end with */. Here are some examples of comments:

/*
 * Styles for main navigation links.
 *
 * @see templates/_navigation.html
 */

.nav-link {
  padding: 4px;
  text-decoration: none;
}

.nav-link:hover {
  border-bottom: 4px solid #000000;

  /*
   * prevents addition of the 4px bottom border
   * from making the element shift
   */
  padding-bottom: 0;
}

/* @deprecated */
.navigation-link {
  color ...

Get CSS Refactoring now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.