导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

算法

UI、组件库

Node

业务技能

针对性攻坚

AI

公共类


代码规范

代码风格

代码格式化

样式书写一般有两种:一种是紧凑格式 (Compact)

.one { display: block;width: 50px; }

一种是展开格式(Expanded)

.one {
  display: block;
  width: 50px;
}

团队约定

统一使用展开格式书写样式

代码大小写

样式选择器,属性名,属性值关键字全部使用小写字母书写,属性字符串允许使用大小写。

/* 推荐 */
.one {
  display: block;
}

/* 不推荐 */
.ONE{
  DISPLAY:BLOCK;
}

选择器

/* 推荐 */
.one {}
.one li {}
.one li p {}

/* 不推荐 */
* {}
#one {}
.one div {}

代码缩进

统一使用 2 个空格进行代码缩进,使得各编辑器表现一致(各编辑器有相关配置)

.one {
  width: 100%;
  height: 100%;
}

分号

每个属性声明末尾都要加分号;

.one {
  width: 100%;
  height: 100%;
}

代码易读性

左括号与类名之间一个空格,冒号与属性值之间一个空格

推荐:

.one {
  width: 100%;
}

不推荐:

.one {
width:100%;
}

逗号分隔的取值,逗号之后一个空格

推荐:

.one {
box-shadow:1px1px1px#333,2px2px2px#ccc;
}

不推荐:

.one {
box-shadow:1px1px1px#333,2px2px2px#ccc;
}

为单个css选择器或新声明开启新行

推荐:

.one,
.one-logo,
.one-hd {
color:#ff0;
}

.nav {
color:#fff;
}

不推荐:

.one,one-logo,.one-hd {
color:#ff0;
}
.nav{
color:#fff;
}

颜色值 rgb() rgba() hsl() hsla() rect() 中不需有空格,且取值不要带有不必要的 0

推荐:

.one {
color:rgba(255,255,255,.5);
}

不推荐:

.one {
color:rgba(255,255,255,0.5 );
}

属性值十六进制数值能用简写的尽量用简写

推荐:

.one {
color:#fff;
}

不推荐:

.one {
color:#ffffff;
}

不要为 0 指明单位

推荐:

.one {
margin:010px;
}

不推荐:

.one {
margin:0px10px;
}

属性值引号

css属性值需要用到引号时,统一使用单引号

/* 推荐 */
.one {
font-family:'Hiragino Sans GB';
}

/* 不推荐 */
.one {
font-family:"Hiragino Sans GB";
}

属性书写顺序

建议遵循以下顺序:

  1. 布局定位属性:display / position / float / clear / visibility / overflow
  2. 自身属性:width / height / margin / padding / border / background
  3. 文本属性:color / font / text-decoration / text-align / vertical-align / white- space / break-word
  4. 其他属性(CSS3):content / cursor / border-radius / box-shadow / text-shadow / background:linear-gradient …
.one {
display: block;
position: relative;
float: left;
width:100px;
height:100px;
margin:010px;
padding:20px0;
font-family: Arial,'Helvetica Neue', Helvetica, sans-serif;
color:#333;
background:rgba(0,0,0,.5);
-webkit-border-radius:10px;
-moz-border-radius:10px;
-o-border-radius:10px;
-ms-border-radius:10px;
border-radius:10px;
}

CSS3浏览器私有前缀写法

CSS3 浏览器私有前缀在前,标准前缀在后

.one {
-webkit-border-radius:10px;
-moz-border-radius:10px;
-o-border-radius:10px;
-ms-border-radius:10px;
border-radius:10px;
}

更多关于浏览器私有前辍写法:#Vendor-specific extensions

注释规范

Comments begin with the characters /* and end with the characters */. They may occur anywhere outside other tokens, and their contents have no influence on the rendering. Comments may not be nested.


/* Comment Text */
.one {}

/* Comment Text */
.one {}

团队约定

单行注释