Bootstrap CSS Coding Standards

Syntax

  • Use two spaces instead of tabs -- this is the only way to ensure consistent rendering in all environments.
  • When grouping selectors, place each individual selector on its own line.
  • For readability, add a space before the opening brace of each declaration block.
  • The closing brace of a declaration block should be on its own line.
  • Each declaration statement's:colon should be followed by a space.
  • For more accurate error reporting, each declaration should be on its own line.
  • All declaration statements should end with a semicolon. The semicolon after the last declaration is optional, but omitting it may make your code more error-prone.
  • For comma-separated property values, insert a space after each comma (e.g.,box-shadow)。
  • Do notrgb()、rgba()、hsl()、hsla()orrect()in a value'sinsideinsert a space after the comma. This helps distinguish multiple color values (commas without spaces) from multiple property values (commas with spaces).
  • For property values or color parameters, omit the leading 0 for decimals less than 1 (e.g.,.5instead of0.5;-.5pxinstead of-0.5px)。
  • Hexadecimal values should be lowercase, e.g.,#fffWhen scanning documents, lowercase characters are easier to distinguish because their forms are more distinct.
  • Use shorthand hexadecimal values where possible, e.g., use#fffinstead of#ffffff。
  • Add double quotes to attributes in selectors, e.g.,input[type="text"]。Quotes are optional only in certain casesHowever, for consistency, it is recommended to always use double quotes.
  • Avoid specifying units for zero values, e.g., usemargin: 0;instead ofmargin: 0px;。

Questions about the terminology used here? See Wikipedia'sCascading Style Sheets - Syntax。

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

Declaration order

Related property declarations should be grouped together and arranged in the following order:

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

Positioning can remove elements from the normal document flow and can override box model related styles, so it is placed first. The box model comes second because it determines the size and position of a component.

Other properties only affect the component'sinsideor do not affect the first two groups, so they are placed later.

For the complete list of properties and their order, please refer toRecess。

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

Don't use@import

and<link>Compared with the tag,@importdirectives are much slower, not only adding extra requests but also causing unpredictable problems. Alternatives include:

  • Use multiple<link>elements
  • Compile multiple CSS files into one file via a CSS preprocessor such as Sass or Less.
  • Through the CSS file merging functionality provided by Rails, Jekyll, or other systems.

Please refer toSteve Souders's articleto learn more.

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

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

Placement of media queries

Place media queries as close as possible to the related rules. Don't package them into a single stylesheet or place them at the bottom of the document. If you separate them, they will only be forgotten in the future. A typical example is given below.

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

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

Prefixed properties

When using vendor-prefixed properties, indent so that each property's value is vertically aligned, making multi-line editing easier.

In Textmate, useText → Edit Each Line in Selection(⌃⌘A). In Sublime Text 2, useSelection → Add Previous Line(⌃⇧↑) andSelection → 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);
}

Single-line rule declarations

Forcontaining only one declarationstyles, for readability and quick editing, it is recommended to put the statements on the same line. For styles with multiple declarations, the declarations should still be split into multiple lines.

The key factor here is error detection -- for example, a CSS validator points out a syntax error at line 183. If it is a single declaration on one line, you will not ignore the error; if it is multiple declarations on one line, you need to analyze carefully to avoid missing errors.

/* 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 property declarations

When you need to explicitly set all values, you should try to limit the use of shorthand property declarations. Common cases of abusing shorthand property declarations are as follows:

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

In most cases, we do not need to specify all values for shorthand property declarations. For example, HTML heading elements only need to set the top and bottom margin values, so when necessary, only override these two values. Overusing shorthand property declarations can cause code confusion and unnecessary overrides of property values, leading to unexpected side effects.

MDN (Mozilla Developer Network) has an excellent article onshorthand propertiesarticle, which is very useful for users who are not familiar with shorthand property declarations and their 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;
}

Nesting in Less and Sass

Avoid unnecessary nesting. This is because although you can use nesting, it does not mean you should. Only use nesting when you must restrict styles to a parent element (i.e., descendant selectors) and there are multiple elements that need nesting.

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

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

Comments

Code is written and maintained by people. Please ensure your code is self-describing, well-commented, and easy for others to understand. Good code comments convey context and purpose. Do not simply restate component or class names.

For longer comments, be sure to write complete sentences; for general annotations, concise phrases are acceptable.

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

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

Class naming

  • Class names should only contain lowercase characters and dashes (not underscores, not camelCase). Dashes should be used for naming related classes (similar to namespaces) (e.g.,.btnand.btn-danger)。
  • Avoid overly arbitrary abbreviations..btnrepresentsbutton, but.sconveys no meaning.
  • Class names should be as short as possible and clearly meaningful.
  • Use meaningful names. Use organized or purpose-driven names, not presentational names.
  • Use the nearest parent class or base class as a prefix for new classes.
  • Use.js-*classes to identify behavior (as opposed to styles), and do not include these classes in CSS files.

You can also refer to the specifications listed above when naming Sass and Less variables.

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

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

Selectors

  • Use classes for generic elements, which is beneficial for rendering performance optimization.
  • For frequently occurring components, avoid attribute selectors (e.g.,[class^="..."]). Browser performance is affected by these factors.
  • Selectors should be as short as possible, and try to limit the number of elements composing a selector; it is recommended not to exceed 3.
  • Onlywhen necessary should you restrict the class to the nearest parent element (i.e., descendant selectors) (e.g., when not using prefixed classes -- the prefix is similar to a namespace).

Further reading:

/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }

Code organization

  • Organize code segments by component.
  • Establish consistent commenting conventions.
  • Use consistent whitespace to separate code into blocks, which aids scanning large documents.
  • If using multiple CSS files, split them by component rather than by page, because pages may be reorganized, while components are only 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 configuration

Configure your editor as follows to avoid common code inconsistencies and diffs:

  • Use two spaces instead of tabs (soft-tab, i.e., spaces instead of tab characters).
  • When saving files, remove trailing whitespace.
  • Set file encoding to UTF-8.
  • Add a blank line at the end of the file.

Refer to the documentation and add these configuration settings to the project's.editorconfigfile. For example:The .editorconfig example in Bootstrap. For more information, refer toabout EditorConfig。

other extensions