Code Guide zh-CN

创建灵活、耐用和可扩展的 HTML 与 CSS 的规范。

目录

HTML

CSS

黄金法则

随时都遵守代码规范,不管是这里的,还是你自己的。无论大小,如果有误还请不吝指出。为 Code Guide 添加或贡献,请在 GitHub 新开讨论

无论参与者有多少,每行代码都应当看起来像一个人所写的一样。

HTML

语法

<!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>

HTML5 doctype

在每一个 HTML 页面中使用这个简洁的 doctype 以保证在任何浏览器下获得一致的渲染效果与执行标准模式。

<!DOCTYPE html>
<html>
  <head>
  </head>
</html>

字符编码

声明一个明确的字符编码可以迅速与简单的确宝正确渲染你的内容。

<head>
  <meta charset="UTF-8">
</head>

CSS 和 JavaScript 的引入

HTML5 规定无须为 CSS 和 JavaScript 的 type 属性指定 text/csstext/javascript的 MIME 类型。

HTML5 规范链接

<!-- External CSS -->
<link rel="stylesheet" href="code-guide.css">

<!-- In-document CSS -->
<style>
  /* ... */
</style>

<!-- JavaScript -->
<script src="code-guide.js"></script>

简洁实用

在实用的前提下,尽量保持 HTML 的标准与语义化。在减少复杂性的前提下尽可能少用标签

属性书写顺序

HTML 属性应当使用如下特定顺序使其更具可读性。

Class 重用性高,所以将它放第一位。Id 更形象具体,应该谨慎使用,(e.g., for in-page bookmarks), 所以将其排在第二。

<a class="..." id="..." data-modal="toggle" href="#">
  Example link
</a>

<input class="form-control" type="text">

<img src="..." alt="...">

布尔值属性

布尔值属性无须声明值,XHTML要求声明一个值,但 HTML5 无此规定。

详细阅读请移步 WhatWG 以下是关于布尔值属性的部分节选:

当一个元素中出现布尔值属性时则值为 true,如果缺失该属性则为 false。

如果你一定要 包含属性的值, 你不用遵守以下 WhatWG 的规范:

如果属性存在,它的值必须为空字符串或[...]该属性名,前后不能有空格。

总之,不要设置值。

<input type="text" disabled>

<input type="checkbox" value="1" checked>

<select>
  <option value="1" selected>1</option>
</select>

减少标签

书写 HTML 要随时避免产生过多的父元素,因为很多时候都需要迭代与重构,所以请按示例中那样来减少 HTML 标签:

<!-- Not so great -->
<span class="avatar">
  <img src="...">
</span>

<!-- Better -->
<img class="avatar" src="...">

JavaScript 生成标签

将标签写在 JavaScript 里面会使得内容变得难以查找、编辑和降低性能,请尽可能避免。

CSS

语法

Questions on the terms used here? See the syntax section of the Cascading Style Sheets article on 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:0 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}

/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
  padding: 15px;
  margin: 0 0 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 following the order:

  1. 位置属性
  2. 自身属性(盒模型)
  3. 文本属性
  4. 显示属性

Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement.

Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.

For a complete list of properties and their order, please see 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;
}

Media query placement

Place media queries as close to their relevant rule sets whenever possible. Don't bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here's a typical setup.

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

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

Prefixed properties

When using vendor prefixed properties, indent each property such that the declaration's value lines up vertically for easy multi-line editing.

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

In instances where a rule set includes only one declaration, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.

The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there's no missing it. With multiple declarations, separate lines is a must for your sanity.

/* 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 notation

Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:

Often times we don't need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.

The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and 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. Just because you can nest, doesn't mean you always should. Consider nesting only if you must scope styles to a parent and if there are multiple elements 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 descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.

Be sure to write in complete sentences for larger comments and succinct phrases for general notes.

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

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

Class names

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

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

Selectors

Additional reading:

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

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

Organization

/*
 * 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 { ... }

编辑器首选项

将编辑器调整为以下设置以避免共同协作时产生的不一致与差别:

你可以考虑为你的项目创建一个 .editorconfig 的文件来书写和应用这些首选项。例如:可以查看 Bootstrap 的使用,或者学习更多关于 EditorConfig 的知识。