Bootstrap CSS Coding Standards
Syntax
- Use two spaces instead of tabs -- this is the only way to guarantee consistent rendering in all environments.
- When grouping selectors, put each individual selector on its own line.
- For code 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.
- A space should be inserted after the
:in each declaration statement. - 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 if you omit it, your code may be more error-prone.
- For comma-separated property values, insert a space after each comma (for example,
box-shadow)。 - Do not use
rgb()、rgba()、hsl()、hsla()orrect()insert a space after commas inside thevalue.This makes it easier to distinguish multiple property values (with both commas and spaces) from multiple color values (with commas only, no spaces). - For property values or color parameters, omit the leading 0 before decimals less than 1 (for example,
.5instead of0.5;-.5pxinstead of-0.5px)。 - Hexadecimal values should all be lowercase, for example,
#fff. When scanning a document, lowercase characters are easier to recognize because their shapes are easier to distinguish. - Use shorthand hexadecimal values whenever possible, for example, use
#fffinstead of#ffffff。 - Add double quotes to attributes in selectors, for example,
input[type="text"]。is only optional in certain cases, but for code consistency, it is recommended to add double quotes everywhere. - Avoid specifying units for zero values, for example, use
margin: 0;instead ofmargin: 0px;。
Do you have questions about the terms used here? Please refer to the Wikipedia article on Cascading 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:
- Positioning
- Box model
- Typographic
- Visual
Since positioning can remove elements from the normal document flow and can override box model related styles, it comes first. The box model comes second because it determines the size and position of components.
Other properties only affect the *inside* of a component or do not affect the first two groups, so they come last.
For the complete list of properties and their ordering, please refer to 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 the @import
The difference between Compared with the tag,@import the directive is much slower, not only adding extra HTTP requests but also causing unpredictable problems. The alternatives are as follows:
- Using multiple
Element - Use a CSS preprocessor like Sass or Less to compile multiple CSS files into one file
- Use the CSS file merging feature provided by Rails, Jekyll, or other systems
Please refer to Steve Souders' articlefor more information.
Placement of media queries
Place media queries as close as possible to the relevant rules. Do not bundle them in a single stylesheet file or put them at the bottom of the document. If you separate them, they will only be forgotten later. 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-specific prefixed properties, use indentation to align the values of each property vertically, which makes multi-line editing easier.
In TextMate, use Text → Edit Each Line in Selection (Ctrl+Cmd+A). In Sublime Text 2, use Selection → Add Previous Line (Ctrl+Shift+Up) 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
Forcontaining only one declarationFor readability and easy editing, it is recommended to put the statement on the same line. For styles with multiple declarations, the declarations should still be split across multiple lines.
The key to doing this is error detection -- for example, a CSS validator points out a syntax error on line 183. With one declaration per line, you will not overlook the error; with multiple declarations on one line, you have 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 limit the use of shorthand property declarations as much as possible. Common cases of abusing shorthand property declarations are as follows:
paddingmarginfontbackgroundborderborder-radius
In most cases, we do not need to specify all values for a shorthand property declaration. For example, HTML heading elements only need the top and bottom margin values set, so when necessary, just override those two values. Overusing shorthand property declarations leads to messy code and unnecessary overrides of property values, causing unexpected side effects.
A very good article on MDN (Mozilla Developer Network) aboutshorthand properties 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 just because you can use nesting does not mean you should. Only use nesting when you must restrict styles to a parent element (that is, 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 { … }
}
Notes
Code is written and maintained by people. Please make sure your code is self-describing, well-commented, and easy for others to understand. Good code comments convey context and code purpose. Do not simply restate component or class names.
For longer comments, be sure to write complete sentences; for general annotations, concise phrases are fine.
/* Bad example */
/* Modal header */
.modal-header {
...
}
/* Good example */
/* Wrapping element for .modal-title and .modal-close */
.modal-header {
...
}
Class naming
- Class names may contain only lowercase characters and dashes (not underscores, and not camel case). Dashes should be used in the naming of related classes (similar to a namespace) (for example,
.btnand.btn-danger)。 - Avoid overly arbitrary abbreviations.
.btnRepresenting button, but.sdoes not express any meaning. - Class names should be as short as possible while still being meaningful.
- Use meaningful names. Use organized or purpose-driven names, not presentational names.
- Prefix new classes with the nearest parent class or a base class.
- Use
.js-*classes to identify behavior (as opposed to styling), and do not include these classes in CSS files.
The guidelines listed above can also be referenced when naming Sass and Less variables.
/* Bad example */
.t { ... }
.red { ... }
.header { ... }
/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }
Selector
- Use classes for generic elements, which helps optimize rendering performance.
- For frequently occurring components, avoid using attribute selectors (for example,
[class^="..."]). Browser performance can be affected by these factors. - Keep selectors as short as possible and limit the number of elements making up a selector; it is recommended not to exceed 3.
- OnlyOnly restrict a class to the nearest parent element (that is, a descendant selector) when necessary (for example, when not using prefixed classes -- a 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 sections by component.
- Establish consistent commenting conventions.
- Use consistent whitespace to separate code into blocks, which makes scanning large documents easier.
- If multiple CSS files are used, split them by component rather than by page, because pages get reorganized while components only get 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 with the following settings to avoid common code inconsistencies and differences:
- Use two spaces instead of tabs (a soft-tab is spaces representing a tab character).
- Remove trailing whitespace when saving files.
- Set the file encoding to UTF-8.
- Add a blank line at the end of the file.
Refer to the documentation and add this configuration information to your project's .editorconfig file. For example:Example .editorconfig in Bootstrap. For more information, please refer to about EditorConfig。