Syntax

  • Use tabs with four spaces—code does not need to be rendered the same in any environment and developers should feel free to choose what works best for them to read
  • 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).
  • Include spaces after commas within rgb(), rgba(), hsl(), hsla(), or rect() values.
  • Prefix property values or color parameters with a leading zero (e.g., 0.5 instead of .5 and -0.5px instead of -.5px).
  • Do not use hex values (prefer rgb() or hsl() but if you must use hex values then lower case them, e.g., #fff. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.
  • Prefer relative units for typography and most properties over fixed units, e.g. rem, em. The one exception is for width and height properties.

  • 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 CSS */
.selector, .selector-secondary, .selector[type=text] {
    margin-bottom: 15px;
    box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
    background-color: rgba(0,0,0,.5);
    padding: 15px;
}

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

Declaration order

Related property declarations should be grouped together following the order:

  1. Display
  2. Positioning
  3. Box model
  4. Typography
  5. Animation

Display properties come first because they determine whether or not a element shows up, thus negating anything coming after it.

Positioning comes next 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 sections, and thus they come last.

For a complete list of properties and their order, please see the property order for our Stylelint.

.declaration-order {
    /* Display */
    display: block;
    opacity: 1;

    /* Positioning */
    flex-basis: 100%;
    flex-direction: column;
    justify-content: space-around;
    float: right;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;

    /* Box-model */
    width: 100px;
    height: 100px;
    margin: 10px;
    border: 1px solid #e5e5e5;
    border-radius: 3px;
    background-color: #f5f5f5;

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

    /* Animation */
    transition: all 3s;
}

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 into a single file
  • Concatenate your CSS files with features provided in NodeJS, Jekyll, or 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>

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 { ... }
}

Prefixed properties

Do not use vendor-prefixed properties; use tools like autoprefixer and browserlist to handle situations like this as it keeps code future proof.

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; }

Shorthand notation

Limit shorthand declaration usage to instances where you must explicitly set all available values. Frequently overused shorthand properties include:

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

Usually 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. A 0 value implies an override of either a browser default or previously specified value.

Excessive use of shorthand properties 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;
    border-radius: 3px 3px 0 0;
    background: red;
    background: url("image.jpg");
}

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

Nesting in 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.

Additional reading:

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

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

Operators in 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;
}

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 {
    ...
}

Class names

  • Keep classes lowercase and use dashes (not underscores nor 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 [data-*] attribute and attribute selectors 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 variable names.

/* Bad example */
.t { ... }
.red { ... }
.header { ... }

/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }

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 { ... }

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.

Tip: Use spiderpig when attempting to change some existing CSS as it allows you to search through a site or application to see which pages are affected.

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