CSS Best Practices

CSS Best Practices


1. Syntax

  • Use soft tabs with two spaces—they’re the only way to guarantee code renders the same in any environment.
  • When grouping selectors, keep individual selectors to a single line.
  • Include one space before the opening brace of declaration blocks for legibility.
  • Place closing braces of declaration blocks on a new line.
  • Include one space after : for each declaration.
  • Each declaration should appear on its own line for more accurate error reporting.
  • End all declarations with a semi-colon. The last declaration’s is optional, but your code is more error prone without it.
  • Comma-separated property values should include a space after each comma (e.g., box-shadow).
  • Don’t include spaces after commas within rgb(), rgba(), hsl(), hsla(), or rect() values. This helps differentiate multiple color values (comma, no space) from multiple property values (comma with space).
  • Don’t prefix property values or color parameters with a leading zero (e.g., .5 instead of 0.5 and -.5px instead of -0.5px).
  • Lowercase all hex values, e.g., #fff. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.
  • Use shorthand hex values where available, e.g., #fff instead of #ffffff.
  • Quote attribute values in selectors, e.g., input[type="text"]. They’re only optional in some cases , and it’s a good practice for consistency.
  • Avoid specifying units for zero values, e.g., margin: 0; instead of margin: 0px;.

Questions on the terms used here? See the syntax section of the Cascading Style Sheets article on Wikipedia.

/* Bad Example */

.selector, .selector-secondary, .selector[type=text] {
  padding:15px;
  margin:0px 0px 15px;
  background-color:rgba(0, 0, 0, 0.5);
  box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}

/* Good Example */

.selector,
.selector-secondary,
.selector[type="text"] {
  padding: 15px;
  margin-bottom: 15px;
  background-color: rgba(0,0,0,.5);
  box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}

2. Declaration order

Related property declarations should be grouped together following the order:

  1. Positioning
  2. Box model
  3. Typographic
  4. Visual

Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component’s dimensions and placement.

Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.

For a complete list of properties and their order, please see Recess .

.declaration-order {
  /* Positioning */
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;

  /* Box-model */
  display: block;
  float: right;
  width: 100px;
  height: 100px;

  /* Typography */
  font: normal 13px "Helvetica Neue", sans-serif;
  line-height: 1.5;
  color: #333;
  text-align: center;

  /* Visual */
  background-color: #f5f5f5;
  border: 1px solid #e5e5e5;
  border-radius: 3px;

  /* Misc */
  opacity: 1;
}

3. Don’t use @import

Compared to <link>s, @import is slower, adds extra page requests, and can cause other unforeseen problems. Avoid them and instead opt for an alternate approach:

  • Use multiple <link> elements
  • Compile your CSS with a preprocessor like Sass or Less into a single file
  • Concatenate your CSS files with features provided in Rails, Jekyll, and other environments

For more information, read this article by Steve Souders .

<!-- Use link elements -->
<link rel="stylesheet" href="core.css">

<!-- Avoid @imports -->
<style>
  @import url("more.css");
</style>

4. Media query placement

Place media queries as close to their relevant rule sets whenever possible. Don’t bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here’s a typical setup.

.element { ... }
.element-avatar { ... }
.element-selected { ... }

@media (min-width: 480px) {
  .element { ...}
  .element-avatar { ... }
  .element-selected { ... }
}

5. Prefixed properties

When using vendor prefixed properties, indent each property such that the declaration’s value lines up vertically for easy multi-line editing.

In Textmate, use Text → Edit Each Line in Selection (⌃⌘A). In Sublime Text 2, use Selection → Add Previous Line (⌃⇧↑) and Selection → Add Next Line (⌃⇧↓).

/* Prefixed properties */
.selector {
  -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
          box-shadow: 0 1px 2px rgba(0,0,0,.15);
}

6. Single declarations

In instances where a rule set includes only one declaration, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.

The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there’s no missing it. With multiple declarations, separate lines is a must for your sanity.

/* Single declarations on one line */
.span1 { width: 60px; }
.span2 { width: 140px; }
.span3 { width: 220px; }

/* Multiple declarations, one per line */
.sprite {
  display: inline-block;
  width: 16px;
  height: 15px;
  background-image: url(../img/sprite.png);
}
.icon           { background-position: 0 0; }
.icon-home      { background-position: 0 -20px; }
.icon-account   { background-position: 0 -40px; }

7. Shorthand notation

Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:

  • padding
  • margin
  • font
  • background
  • border
  • border-radius

Often times we don’t need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.

The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and behavior.

/* Bad example */

.element {
  margin: 0 0 10px;
  background: red;
  background: url("image.jpg");
  border-radius: 3px 3px 0 0;
}

/* Good example */

.element {
  margin-bottom: 10px;
  background-color: red;
  background-image: url("image.jpg");
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}

8. Nesting in Less and Sass

Avoid unnecessary nesting. Just because you can nest, doesn’t mean you always should. Consider nesting only if you must scope styles to a parent and if there are multiple elements to be nested.

// Without nesting
.table > thead > tr > th {  }
.table > thead > tr > td {  }

// With nesting
.table > thead > tr {
  > th {  }
  > td {  }
}

9. Operators in Less and Sass

For improved readability, wrap all math operations in parentheses with a single space between values, variables, and operators.

/* Bad example */


.element {
  margin: 10px 0 @variable*2 10px;
}

/* Good example */

.element {
  margin: 10px 0 (@variable * 2) 10px;
}

10. Comments

Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.

Be sure to write in complete sentences for larger comments and succinct phrases for general notes.

/* Bad example */

/* Modal header */
.modal-header {
  ...
}

/* Good example */

/* Wrapping element for .modal-title and .modal-close */
.modal-header {
  ...
}

11. Class names

  • Keep classes lowercase and use dashes (not underscores or camelCase). Dashes serve as natural breaks in related class (e.g., .btn and .btn-danger).
  • Avoid excessive and arbitrary shorthand notation. .btn is useful for button, but .s doesn’t mean anything.
  • Keep classes as short and succinct as possible.
  • Use meaningful names; use structural or purposeful names over presentational.
  • Prefix classes based on the closest parent or base class.
  • Use .js-* classes to denote behavior (as opposed to style), but keep these classes out of your CSS.

It’s also useful to apply many of these same rules when creating Sass and Less variable names.

/* Bad example */

.t { ... }
.red { ... }
.header { ... }

/* Good example */

.tweet { ... }
.important { ... }
.tweet-header { ... }

12. Selectors

  • Use classes over generic element tag for optimum rendering performance.
  • Avoid using several attribute selectors (e.g., [class^="..."]) on commonly occuring components. Browser performance is known to be impacted by these.
  • Keep selectors short and strive to limit the number of elements in each selector to three.
  • Scope classes to the closest parent only when necessary (e.g., when not using prefixed classes).

Additional reading:

/* Bad example */

span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */

.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }

13. Organization

  • Organize sections of code by component.
  • Develop a consistent commenting hierarchy.
  • Use consistent white space to your advantage when separating sections of code for scanning larger documents.
  • When using multiple CSS files, break them down by component instead of page. Pages can be rearranged and components moved.
/*
 * Component section heading
 */

.element { ... }


/*
 * Component section heading
 *
 * Sometimes you need to include optional context for the entire component. Do that up here if it's important enough.
 */

.element { ... }

/* Contextual sub-component or modifer */
.element-heading { ... }

14. Editor preferences

Set your editor to the following settings to avoid common code inconsistencies and dirty diffs:

  • Use soft-tabs set to two spaces.
  • Trim trailing white space on save.
  • Set encoding to UTF-8.
  • Add new line at end of files.

Consider documenting and applying these preferences to your project’s .editorconfig file. For an example, see the one in Bootstrap. Learn more about EditorConfig .

15. Using every declaration just once

A logical way to make your website faster is to make the client code you send to the browser smaller. When looking to optimize your CSS files, one of the most powerful measures you can employ is to use every declaration just once.

Using every declaration just once means making strict use of selector grouping.

For example, you can combine these rules:

h1 { color: black; }
p { color: black; }

into a single rule:

h1, p { color: black; }

While this simple example appears obvious, things are getting more interesting and harder to quantify when talking about complex style sheets. In our experience, using every declaration just once can reduce the CSS file size by 20-40% on average.

Let’s have a look at another example:

h1, h2, h3 { font-weight: normal; }
a strong { font-weight: normal !important; }
strong { font-style: italic; font-weight: normal; }
#nav { font-style: italic; }
.note { font-style: italic; }

Applying the “any declaration just once” rule here results in:

h1, h2, h3, strong { font-weight: normal; }
a strong { font-weight: normal !important; }
strong, #nav, .note { font-style: italic; }

Note that the !important declaration makes a difference.

There are some things to keep in mind when applying this method:

  • First, overly long selectors can render this method useless. Repeating selectors like html body table tbody tr td p span.example in order to have unique declarations doesn’t save much file size. In fact, since “using every declaration just once” might mean a higher number of selectors, this could even result in a bigger style sheet. Using more compact selectors would help, and would enhance the readability of your stylesheet.
  • Second, be aware of CSS regulations. When a user agent can’t parse the selector, it must ignore the declaration block as well . If you run into trouble with this, just bend the “declaration just once” rule – and use it more than once.
  • Third, and most importantly, keep the cascade in mind. No matter if you’re sorting your style sheets in a certain way or are very relaxed about the order in which rules appear in your style sheets, using every declaration once will make you change the order of the rules in one way or another. This order, however, can be decisive for a browser to decide which rule to apply. The easiest solution if you’re running into any issues with this is to make an exception as well and use the declaration in question more than once.

Alas, this is not always trivial to implement – this may change the cascading order and require a different workflow.

Workflow

“Using every declaration just once” requires more attention when maintaining stylesheets. You will benefit from finding a way to track changed and added declarations to get them in line again. This is not hard when using a more or less reasonable editor (showing line changes, for example), but needs to be incorporated into the workflow.

One way, for instance, is to mark rules you edited or added by indenting them. Once you’re done updating your stylesheet, you can check for the indented rules to see if there are any new duplicate declarations, which you could then move to make sure each one of them is only used once.

16. Resources

  • Bootstrap Framework

    Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web and the one AHA/ASA uses for production.

Leave a Comment