English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Bootstrap CSS Coding Standards

语法

  • Replace tabs (tab) with two spaces -- This is the only method that can ensure consistent display in all environments.
  • When grouping selectors, place the individual selector on a separate line.
  • To improve code readability, add a space before the left curly brace of each declaration block.
  • The right curly brace of the declaration block should be on a separate line.
  • Each declaration statement's : 后应该插入一个空格。
  • 为了获得更准确的错误报告,每条声明都应该独占一行。
  • 所有声明语句都应当以分号结尾。最后一条声明语句后面的分号是可选的,但是,如果省略这个分号,你的代码可能更易出错。
  • 对于以逗号分隔的属性值,每个逗号后面都应该插入一个空格(例如,box-shadow).
  • 不要在 rgb()rgba()hsl()hsla()rect() 值的内部的逗号后面插入空格。这样利于从多个属性值(既加逗号也加空格)中区分多个颜色值(只加逗号,不加空格)。
  • 对于属性值或颜色参数,省略小于 1 的小数前面的 0 (例如,.5 代替 0.5-.5px 代替 -0.5px).
  • 十六进制值应该全部小写,例如,#fff。在扫描文档时,小写字符易于分辨,因为他们的形式更易于区分。
  • 尽量使用简写形式的十六进制值,例如,用 #fff 代替 #ffffff.
  • 为选择器中的属性添加双引号,例如,input[type="text"].只有在某些情况下是可选的,但是,为了代码的一致性,建议都加上双引号。
  • 避免为 0 值指定单位,例如,用 margin: 0; 代替 margin: 0px;.

对于这里用到的术语有疑问吗?请参考 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;
}

声明顺序

相关的属性声明应当归为一组,并按照下面的顺序排列:

  • Positioning
  • Box model
  • Typographic
  • Visual
  • 由于定位(positioning)可以从正常的文档流中移除元素,并且还能覆盖盒模型(box model)相关的样式,因此排在首位。盒模型排在第二位,因为它决定了组件的尺寸和位置。

    其他属性只是影响组件的内部(inside)or do not affect the first two groups of properties, so they are placed at the end.

    Please refer to the complete list of attributes and their order 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;
    }
    

    Do not use @import

    with <link> tags compared to@import Instructions are much slower, not only increasing the number of additional requests but also causing unpredictable problems. Alternative solutions include the following:

    • Using multiple <link> Elements
    • Compile multiple CSS files into one file using pre-processors like Sass or Less
    • CSS file merging functionality provided by systems such as Rails, Jekyll, or others

    Please refer to Steve Souders' articleLearn more.

    <!-- Use link elements -->
    <link rel="stylesheet" href="core.css">
    <!-- Avoid @imports -->
    <style>
      @import url("more.css");
    </style>
    

    Position of media query (Media query)

    Place media queries as close as possible to the related rules. Do not pack them into a single style sheet or place them at the bottom of the document. If you separate them, they will be easily forgotten in the future. Below is a typical example.

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

    Prefixed attributes

    When using attributes with prefixes from specific vendors, align each attribute's value vertically through indentation to facilitate multi-line editing.

    In Textmate, use Text → Edit Each Line in Selection (⌃⌘A). In Sublime Text 2 in, 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);
    }
    

    single-line rule declarations

    ForContains only one declarationstyles, for readability and ease of quick editing, it is recommended to place statements on the same line. For styles with multiple declarations, it is still recommended to divide the declarations into multiple lines.

    The key factor for this is error detection -- For example, the CSS validator points out that in 183 Lines have syntax errors. If it is a single-line single declaration, you would not ignore this error; if it is a single-line multiple declarations, 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

    In cases where it is necessary to explicitly set all values, it is recommended to limit the use of shorthand property declarations as much as possible. Common cases of misuse of 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, the HTML heading element only needs to set the values of the top and bottom margins (margin), so when necessary, only these two values need to be overridden. Overusing shorthand property declarations can lead to code confusion and unnecessary overrides of property values, causing unexpected side effects.

    MDN (Mozilla Developer Network) has a very good article aboutshorthand properties is very useful for users who are not familiar with shorthand property declarations and their behaviors.

    /* 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 while you can use nesting, it does not mean that you should use nesting. Use nesting only when it is necessary to restrict styles within the parent element (i.e., descendant selectors) and there are multiple elements that need to be nested.

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

    Comments

    Code is written and maintained by humans. Ensure that your code is self-explanatory, well-commented, and easy for others to understand. Good code comments can convey context and the purpose of the code. Do not simply restate component or class names.

    For longer comments, always write complete sentences; for general annotations, concise phrases can be used.

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

    Class Naming

    • Only lowercase characters and dashes (not underscores, nor camelCase) should appear in class names. Dashes should be used in naming related classes (similar to namespaces) such as,.btn and .btn-danger).
    • Avoid overly arbitrary abbreviations..btn represents button, but .s They should not express any meaning.
    • Class names should be as short as possible and clearly meaningful.
    • Use meaningful names. Use organized or purpose-specific names; do not use presentational names.
    • Use the nearest parent class or the basic (base) class as a prefix for the new class.
    • Use .js-* Use 'class' to identify behaviors (in contrast to styles), and do not include these classes in CSS files.

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

    /* Bad example */
    .t { ... }
    .red { ... }
    .header { ... }
    /* Good example */
    .tweet { ... }
    .important { ... }
    .tweet-header { ... }
    

    Selectors

    • Use class for generic elements to facilitate rendering performance optimization.
    • Avoid using attribute selectors for frequently occurring components (for example,[class^="..."]). Browser performance can be affected by these factors.
    • Selectors should be as short as possible and limit the number of elements in the selector composition, it is recommended not to exceed 3 .
    • OnlyLimit the class to the nearest parent element only when necessary (i.e., using descendant selectors) (for example, do not use prefixed classes when -- Prefixes are similar to namespaces).

    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 sections by component.
    • Establish consistent comment conventions.
    • Use consistent whitespace to separate code blocks, which is helpful for scanning larger documents.
    • If multiple CSS files are used, split them by component rather than by page, because pages will be restructured, while components will only be 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 differences:

    • Replace tabs with two spaces (soft)-tab represents the tab character.)
    • Remove trailing whitespace when saving the file.
    • Set the file encoding to UTF-8.
    • Add an empty line at the end of the file.

    Refer to the document and add these configuration information to the project's .editorconfig For example:Bootstrap .editorconfig Example in the file.. For more information, please refer to about EditorConfig.