No matter how many people work on the same project, make sure every line of code looks like it was written by the same person.
1. Use two spaces instead of tabs - this is the only way to ensure consistent display in all environments.
2. Nested elements should be indented once (i.e. two spaces).
3. For the definition of attributes, make sure to use double quotes and never use single quotes.
4. Don’t add a trailing slash to a self-closing element – the HTML5 specification clearly states that this is optional.
5. Don’t omit the optional closing tag
<!DOCTYPE html> <html> <head> <title>Page title</title> </head> <body> <img src="images/company-logo.png" alt="Company"> <h1 class="hello-world">Hello, world!</h1> </body> </html>
Add a standard mode declaration to the first line of every HTML page to ensure consistent presentation in every browser.
<!DOCTYPE html> <html> <head> </head> </html>
According to the HTML5 specification:
It is strongly recommended to specify the lang attribute for the html root element to set the correct language for the document. This will help speech synthesis tools determine the pronunciation they should use, help translation tools determine the rules they should follow when translating, and so on.
<html lang="en-us"> <!-- ... --> </html>
IE supports specific tags to determine the IE version that should be used to draw the current page. Unless there are strong special needs, it is best to set it to edge mode to notify IE to adopt the latest mode it supports.
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
By explicitly declaring the character encoding, you can ensure that the browser quickly and easily determines how the page content should be rendered. The advantage of this is that you can avoid using character entities in HTML, so that everything is consistent with the document encoding (usually UTF-8 encoding).
<head> <meta charset="UTF-8"> </head>
According to the HTML5 specification, there is generally no need to specify the type attribute when introducing CSS and JavaScript files, because text/css and text/javascript are their default values respectively.
<!-- External CSS --> <link rel="stylesheet" href="code-guide.css"> <!-- In-document CSS --> <style> /* ... */ </style> <!-- JavaScript --> <script src="code-guide.js"></script>
Try to follow HTML standards and semantics, but don't sacrifice practicality. Try to use the fewest tags and keep complexity to a minimum at all times.
HTML attributes should be arranged in the order given below to ensure the readability of the code.
class
ID, name
data-*
src, for, type, href, value
title, alt
role, aria-*
class is used to identify highly reusable components, so it should be listed first. The id is used to identify a specific component and should be used with caution (for example, bookmarks within a page), so it comes second.
Boolean properties can be declared without a value. The XHTML specification requires it to be assigned a value, but the HTML5 specification does not.
For more information please refer to the WhatWG section on boolean attributes:
If a Boolean attribute of an element has a value, it is true; if it has no value, it is false.
If you must assign a value to it, please refer to the WhatWG specification:
If the attribute exists, its value must be the empty string or […] the canonical name of the attribute, with no leading or trailing whitespace.
To put it simply, there is no need to assign a value.
When writing HTML code, try to avoid redundant parent elements. Many times, this requires iteration and refactoring to achieve. Please see the following case:
<!-- Not so great --> <span class="avatar"> <img src="..."> </span> <!-- Better --> <img class="avatar" src="...">
Tags generated through JavaScript make content difficult to find, edit, and slow down performance. Avoid it when you can.
1. Use two spaces instead of tabs - this is the only way to ensure consistent display in all environments.
2. When grouping selectors, place individual selectors on their own line.
3. For code readability, add a space before the opening brace of each declaration block.
4. The closing curly brace of the declaration block should be on a separate line.
5. A space should be inserted after: in each declaration statement.
6. For more accurate error reporting, each statement should be on its own line.
7. All declaration statements should end with a semicolon. The semicolon after the last declaration statement is optional, but if you omit it, your code may be more error-prone.
8. For comma-separated attribute values, a space should be inserted after each comma (for example, box-shadow).
9. Do not insert spaces after commas inside rgb(), rgba(), hsl(), hsla(), or rect() values. This helps distinguish multiple color values (comma only, no spaces) from multiple attribute values (comma and space).
10. For attribute values or color parameters, omit the leading 0 for decimals less than 1 (for example, .5 instead of 0.5; -.5px instead of -0.5px).
11/Hex values should be all lowercase, for example, #fff. Lowercase characters are easier to read when scanning a document because their form is easier to distinguish.
12. Try to use abbreviated hexadecimal values, for example, use #fff instead of #ffffff.
13. Add double quotes for the attributes in the selector, for example, input[type="text"]. It is only optional in some cases, but for code consistency it is recommended to use double quotes.
14. Avoid specifying units for 0 values, for example, use margin: 0; instead of margin: 0px;.
/* 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; }
Related property declarations should be grouped together and arranged in the following order:
Positioning
Box model
Typographic
Visual
Positioning comes first because it removes elements from the normal document flow and can override box model related styles. The box model comes second because it determines the size and placement of components.
Other properties only affect the inside of the component or do not affect the first two groups of properties, so they are ranked behind.
.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; }
Compared with tags, the @import directive is much slower, which not only increases the number of additional requests, but also causes unpredictable problems. Alternatives include the following:
Compile multiple CSS files into one file through a CSS preprocessor similar to Sass or Less. CSS file merging functions are provided through Rails, Jekyll or other systems.
<!-- Use link elements --> <link rel="stylesheet" href="core.css"> <!-- Avoid @imports --> <style> @import url("more.css"); </style>
Place media queries as close to relevant rules as possible. Don't package them in a single style file or put them at the bottom of the document. If you separate them, they will only be forgotten by everyone in the future. A typical example is given below.
.element { ... } .element-avatar { ... } .element-selected { ... } @media (min-width: 480px) { .element { ...} .element-avatar { ... } .element-selected { ... } }
For styles that contain only one statement, it is recommended to place the statement on the same line for legibility and quick editing. For styles with multiple declarations, the declarations should still be divided into multiple lines.
The key factor in doing this is for error detection - for example, the CSS validator indicates that there is a syntax error on line 183. If it is a single statement on a single line, you will not ignore the error; if it is multiple statements on a single line, you must analyze it 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; }
In cases where you need to set all values explicitly, you should try to limit the use of shorthand property declarations. Common abuses of abbreviated property declarations include the following:
padding
margin
font
background
border
border-radius
In most cases, we don't need to specify all values for a shorthand property declaration. For example, the HTML heading element only needs to set the top and bottom margin values, so you only need to override these two values when necessary. Excessive use of shorthand property declarations can lead to cluttered code and can cause unintended side effects by causing unnecessary overrides of property values.
/* 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; }
Avoid unnecessary nesting. This is because although you can use nesting, it doesn't mean you should. Use nesting only when styles must be restricted to 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 { … } }
To improve readability, add a space between the values, variables, and operators of mathematical expressions enclosed in parentheses.
// Bad example .element { margin: 10px 0 @variable*2 10px; } // Good example .element { margin: 10px 0 (@variable * 2) 10px; }
Code is written and maintained by people. Make sure your code is self-describing, well-commented, and easy for others to understand. Good code comments convey context and purpose of the code. Don't simply restate component or class names.
For longer comments, be sure to write complete sentences; for general comments, you can write concise phrases.
/* Bad example */ /* Modal header */ .modal-header { ... } /* Good example */ /* Wrapping element for .modal-title and .modal-close */ .modal-header { ... }
1. Only lowercase characters and dashes (not underscores, nor camel case) can appear in class names. Dashes should be used in naming related classes (similar to namespaces) (for example, .btn and .btn-danger).
2. Avoid overly arbitrary abbreviations. .btn represents button, but .s cannot express any meaning.
3.Class names should be as short as possible and have clear meaning.
4. Use meaningful names. Use names that are organized or purposeful, not presentational.
5. Based on the nearest parent class or base class as the prefix of the new class.
6. Use .js-* classes to identify behaviors (as opposed to styles), and do not include these classes into CSS files.
/* Bad example */ .t { ... } .red { ... } .header { ... } /* Good example */ .tweet { ... } .important { ... } .tweet-header { ... }
Use classes for common elements, which will help optimize rendering performance.
For frequently occurring components, avoid using attribute selectors (for example, [class^=”…”]). Browser performance can be affected by these factors.
The selector should be as short as possible, and try to limit the number of elements that make up the selector. It is recommended not to exceed 3.
Restrict classes to the nearest parent element (i.e., descendant selector) only when necessary (for example, when not using prefixed classes - prefixes are like namespaces).
/* Bad example */ span { ... } .page-container #stream .stream-item .tweet .tweet-header .username { ... } .avatar { ... } /* Good example */ .avatar { ... } .tweet-header .username { ... } .tweet .avatar { ... }
Set up your editor as follows to avoid common code inconsistencies and differences:
Use two spaces to replace tab characters (soft-tab means using spaces to represent tab characters). When saving the file, remove trailing whitespace characters. Set the file encoding to UTF-8. Adds a blank line to the end of the file.
Refer to the documentation and add this configuration information to your project's .editorconfig file. For example: .editorconfig instance in Bootstrap. For more information, see about EditorConfig.