Skip to content
Juozas Rastenis edited this page Mar 25, 2019 · 4 revisions

CSS (PostCSS)

Table of Contents

Syntax
Media Query Placement
Prefixed properties
Rules with single declarations
Shorthand notation
Specificity
PostCSS
BEM in PostCSS
Nesting in PostCSS and Sass
Operators in PostCSS and Sass
Comments
Classes
Selectors
Organization

Syntax

  • We use soft tabs with four spaces.
  • Nested elements should be indented once (four spaces).
  • 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.
  • Comma-separated property values should include a space after each comma (e.g., box-shadow).
  • 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 CSS */
.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 CSS */
.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;
}

Media query placement

Place media queries inside 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.

/* Bad example */
.block {
    ...

    &__element {...}
    &--modifier {...}
}

@media (min-width:@screen-md) {
    .block {
        ...

        &__element {...}
        &--modifier {...}
    }
}

/* Good example */
.block {
    ...

    @media (min-width:@screen-md) {...}

    &--modifier {
        ...

        @media (min-width:@screen-md) {...}
    }

    &__element {
        ...

        @media (min-width:@screen-md) {...}
    }
}

Prefixed properties

It shouldn't be neccessary to add vendor prefixes, as its handled through gulp setup.

But, in the rare occasion you do need to, indent each property such that the declaration's value lines up vertically for easy multi-line editing.

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

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

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

Specificity

Specificity in CSS relates to the selectors of your class definition. The more specific your selectors are, the more power they have over what is used, and what isn't.

Using ID's (#) will always trump over classses (.), that's even if you have 1000+ class selectors. ID always wins.

Try to avoid the following:

  • Using IDs in your CSS
  • Nesting selectors
  • Chaining selectors
/**
 * Example of most specific definitions
 */

#textpage form {/*Will select every form in #textpage*/}

.new-form {
    // Will get overwritten by the above definition, #textpage form
    // This means we have to add #textpage infront of our class if we want to overrule
}

#textpage form.new-form {/*This, is now the most specific definition*/}

/**
 * Avoid the following
 */

// Using IDs in your CSS
#textpage {...}

// Nesting selectors
.button {
    ...
    .text {...}
}

// Chaining selectors
.button .text {...}

PostCSS

We use postCss and CSSNext as our CSS processor. For a complete feature list, please refer to their documentation.

Variables

Variables are native CSS custom properties. All variable names should be in spinal-case, just like in CSS classes.

If you use a variable declared in another css file, you must reference the variable in the current file, and then add a fallback value in the declaration. The syntax is: var(--some-var, fallback);

You can use variables like this:

Setting

:root {
    --some-class-color: red;
    --some-class-background: var(--color-primary, #bada55);
    --some-class-font-size: var(--font-size-base, 18px);
}

Getting

.some-class {
    color: var(--some-class-color);
    background: var(--some-class-background);
    font-size: var(--some-class-font-size);
}

Colors

See the complete list of color manipulation features here.

Here's a couple of examples:

Transparent color

.some-class {
    color: color(var(--color-primary) alpha(90%));
}

Darken color

.some-class {
    color: color(var(--color-primary) shade(10%));
}

Media queries

NOTE It is not possible to use a CSS custom property (variable) in the declaration of the media queries. Media queries are declared in the variables/settings-file. This is how you use it:

Setting

@custom-media --viewport-sm-min (min-width: 768px);

Getting

.some-class {
    color: blue;
    
    @media(--viewport-sm-min){
        color:red;
    }
}

Using variable in media queries

When using variables inside media queries, make sure to add a selector. If you want to style the "current element", you can use the &-symbol for inheriting:

.some-class {
    color: var(--color-primary);
    
    @media(--viewport-md-min){
        & {
           color: var(--color-secondary);
        }
    }
}

BEM in PostCSS

The following is an example of a breadcrumb, written in PostCSS with a BEM twist.

While writing the PostCSS, it's nested, which keeps it in the same scope and therefore makes it readable.

The & operator takes the parent selector, but when compiled, it's not nested anymore. This means no specificity collisions!

/* Example of BEM in PostCSS */

// Block
.breadcrumb {
    padding: 10px;
    margin-bottom: 30px;

    // Element
    &__link {
        display: inline-block;

        & + &:before {
            content: "/";
            padding-top: 5px;
            padding: 5px 0;
            color: #666;
        }

        // Modifier
        &--active {color: #000;}
    }
}

Nesting in PostCSS and Sass

As a part of the BEM methodology, we never nest. There are rare occasions where nesting is unavoidable, or when it does make sense. But, in general, do not nest.

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

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

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

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 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 PostCSS variable names.
/* Bad example */
.t { ... }
.red { ... }
.header { ... }

/* Good example */
.tweet { ... }
.primary { ... }
.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.
/**
 * 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 { ... }

Editor preferences

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

  • Use soft-tabs set to four 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. You can use this as a starting point.

Learn more about EditorConfig

root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true