Table of Contents
HTML
- Syntax
- HTML5 doctype
- Language Attribute
- Character Encoding
- IE Compatibility Mode
- Including CSS and JavaScript Files
- Pragmatism
- Attribute Order
- Boolean Attributes
- Reduce the Number of Tags
- Tags Generated by JavaScript
CSS
- Syntax
- Declaration Order
- Placement of Media Queries
- Prefixed Properties
- Single-Line Rule Declarations
- Shorthand Property Declarations
- Nesting in Less and Sass
- Comments
- class Naming
- Selectors
- Code Organization
Golden Rule
A project should always follow the same set of coding standards!
No matter how many people are involved in the same project, make sure every line of code looks like it was written by the same person.
HTML
Syntax
- Use two spaces instead of tabs — this is the only way to guarantee consistent rendering across all environments.
- Nested elements should be indented once (i.e., two spaces).
- For attribute definitions, always use double quotes, never single quotes.
- Do not add a trailing slash to self-closing elements —the HTML5 specificationexplicitly states that this is optional.
- Do not omit optional closing tags (for example,
</li>or</body>)。
<!DOCTYPE html>
<html>
<head>
<title>Page title</title>
</head>
<body>
<img src="images/company-logo.png.html" alt="Company">
<h1 class="hello-world">Hello, world!</h1>
</body>
</html>
HTML5 doctype
Add a standard mode declaration as the first line of every HTML page to ensure consistent rendering in every browser.
<!DOCTYPE html> <html> <head> </head> </html>
Language Attribute
According to the HTML5 specification:
It is strongly recommended that you specify the lang attribute on the html root element to set the correct language for the document. This will help speech synthesis tools determine the pronunciation they should use, and help translation tools determine the rules they should follow when translating, among other benefits.
More aboutlangthe attribute can be learned fromthis specificationfor details.
Listed here is thelanguage code table.。
<html lang="zh-CN"> <!-- ... --> </html>
IE Compatibility Mode
IE supports using a specific<meta><meta> tag to determine which IE version should be used to render the current page. Unless there are strong special requirements, it is best to set it toedge modethereby telling IE to use the latest mode it supports.
Read this Stack Overflow articlefor more useful information.
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
Character Encoding
By explicitly declaring the character encoding, you can ensure that browsers can quickly and easily determine how to render the page content. The benefit is that it avoids the need to use character entity marks in HTML, thus remaining consistent with the document encoding (generally UTF-8).
<head> <meta charset="UTF-8"> </head>
Including CSS and JavaScript Files
According to the HTML5 specification, when including CSS and JavaScript files, you generally do not need to specify thetypetype attribute, becausetext/cssandtext/javascriptthey are their respective default values.
HTML5 spec links
<!-- External CSS --> <link rel="stylesheet" href="code-guide.css.html"> <!-- In-document CSS --> <style> /* ... */ </style> <!-- JavaScript --> <script src="code-guide.js.html"></script>
Pragmatism
Follow HTML standards and semantics as much as possible, but do not sacrifice practicality. Always try to use the fewest tags and maintain the least complexity.
Attribute Order
HTML attributes should be arranged in the order given below to ensure code readability.
classid,namedata-*src,for,type,hreftitle,altaria-*,role
class is used to identify highly reusable components, so it should be placed first. id is used to identify specific components and should be used with caution (e.g., in-page bookmarks), so it is placed second.
<a class="..." id="..." data-modal="toggle" href="../index.html"> Example link </a> <input class="form-control" type="text"> <img src="....html" alt="...">
Boolean Attributes
Boolean attributes can be declared without a value. The XHTML specification requires a value, but the HTML5 specification does not.
For more information, please refer toWhatWG section on boolean attributes:
A Boolean attribute on an element is true if it has a value, and false if it has no value.
Ifyou absolutelymust assign a value, please refer to the WhatWG specification:
If the attribute exists, its value must be either an empty string or the canonical name of the attribute, and no trailing whitespace should be added.
Simply put, just don't assign a value.
<input type="text" disabled> <input type="checkbox" value="1" checked> <select> <option value="1" selected>1</option> </select>
Reduce the Number of Tags
When writing HTML code, try to avoid unnecessary parent elements. Often, this requires iteration and refactoring. See the example below:
<!-- Not so great --> <span class="avatar"> <img src="....html"> </span> <!-- Better --> <img class="avatar" src="....html">
Tags Generated by JavaScript
Tags generated by JavaScript make content hard to find and edit, and reduce performance. Avoid them when possible.
CSS
Syntax
- Use two spaces instead of tabs — this is the only way to guarantee consistent rendering in all environments.
- When grouping selectors, place 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.
- Each declaration statement's
:colon should be followed by a space. - To get more accurate error reports, 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
rgb()、rgba()、hsl()、hsla()orrect()insert a spaceinsidea value after a comma. This helps distinguish between multiple property values (comma plus space) and multiple color values (comma only, no space). - For property values or color parameters, omit the leading 0 for decimals less than 1 (for example,
.5instead of0.5;-.5pxinstead of-0.5px)。 - Hexadecimal values should be all lowercase, for example,
#fff. When scanning a document, lowercase characters are easier to recognize because their forms are more distinguishable. - Try to use shorthand hexadecimal values, for example, use
#fffinstead of#ffffff。 - Add double quotes to attributes in selectors, for example,
input[type="text"]。is optional only in certain cases, but for code consistency, it is recommended to always include double quotes. - Avoid specifying units for zero values, for example, use
margin: 0;instead ofmargin: 0px;。
Have questions about the terminology used here? Please refer to Wikipedia'ssyntax section of the Cascading Style Sheets article。
/* 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 also override box model–related styles, it is placed first. The box model comes second because it determines the size and position of components.
Other attributes 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 to the <link> tag,@importthe @import directive is much slower; it not only adds extra requests but also causes unpredictable problems. There are several alternatives:
- Use multiple
<link>elements - Compile multiple CSS files into one file via a CSS preprocessor such as Sass or Less.
- The CSS file concatenation feature provided by Rails, Jekyll, or other systems
Please refer toSteve Souders' articlefor more information.
<!-- 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 to their related rules as possible. Do not bundle them into a single stylesheet or at the bottom of the document. If you separate them, they will only be forgotten in the future. Below is a typical example.
.element { ... }
.element-avatar { ... }
.element-selected { ... }
@media (min-width: 480px) {
.element { ...}
.element-avatar { ... }
.element-selected { ... }
}
Prefixed Properties
When using vendor-specific prefixed properties, indent so that each property's value is aligned vertically, which makes 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
Forstyles with only one declaration, it is recommended to put the statement on one line for readability and quick editing. For styles with multiple declarations, the declarations should still be split across multiple lines.
The key factor is error detection – for example, a CSS validator points out a syntax error on line 183. If it is a single declaration on a single line, you will not overlook the error; if there are multiple declarations on a single line, you need to analyze carefully to avoid missing the error.
/* 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 all values need to be explicitly set, try to limit the use of shorthand property declarations. Common abuses of shorthand property declarations are as follows:
paddingmarginfontbackgroundborderborder-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 top and bottom margin values, so when necessary, just override those two values. Overuse of shorthand property declarations can lead to messy code and may cause unexpected side effects from unnecessary overrides of property values.
A very good article on MDN (Mozilla Developer Network) aboutshorthand propertiesis 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 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 people. Ensure your code is self-descriptive, 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, 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 or camelCase). Dashes should be used for naming related classes (similar to namespaces) (e.g.,
.btnand.btn-danger)。 - Avoid overly arbitrary abbreviations.
.btnrepresentsbutton, but.sdoes not convey any meaning. - Class names should be as short as possible and clearly meaningful.
- Use meaningful names. Use organizational or purpose-based 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 style), and do not include these classes in CSS files.
When naming Sass and Less variables, you can also refer to the specifications listed above.
/* Bad example */
.t { ... }
.red { ... }
.header { ... }
/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }
Selectors
- Use classes for common elements, which is beneficial for rendering performance optimization.
- Avoid attribute selectors for frequently occurring components (e.g.,
[class^="..."]). Browser performance is affected by these factors. - Keep selectors as short as possible and limit the number of elements in a selector, preferably no more than 3.
- Onlyrestrict classes to the nearest parent element when necessary (i.e., descendant selectors) (for example, when not using prefixed classes – 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 segments by component.
- Establish consistent comment conventions.
- Use consistent whitespace to separate code into blocks, which helps with scanning larger documents.
- If multiple CSS files are used, split them by component rather than by page, because pages can 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 differences:
- Use two spaces instead of tabs (soft-tab, i.e., spaces represent tab characters).
- 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 the project's.editorconfigfile. For example:An .editorconfig example from Bootstrap. For more information, please refer toabout EditorConfig。