css 代码规范

来源:互联网 发布:vmware nat 端口转发 编辑:程序博客网 时间:2024/06/07 01:13

通用原则

  • 缩进: 两个空格
  • 命名均使用小写字母,多个单词之间用 - 分隔
  • 空格:
    • 在每个声明块的左花括号前添加一个空格
    • 每条声明语句的 : 后应该插入一个空格
  • 声明块的右花括号单独成行
  • 每条声明都应该独占一行
  • 所有声明语句都应当以分号结尾
.selector {  margin: 0;  padding: 0;

}

选择器

尽量都使用 class 来命名 css 样式, 少用 id。

同 html 代码保持一致的命名风格。

  • class 名称中均使用小写字母,并且多个字母之间用 - 破折号连接
  • class 命名需具备明确的语义并尽可能短,但是不能过分简短
/* meaningless, BAD */.t { ... }.red { ... }
/* meaningful, GOOD */.tip { ... }.warning { ... }
  • 避免元素选择器和类选择器以及 ID 选择器的混用
/* BAD */ul#list {}ul.list {}
/* GOOD */#list {}.list {}
  • 例外: 作为 JS 接口的 class 或者 ID,必须是以 J- 前缀开头的


格式规范

  1. 在每个声明块的左花括号前添加一个空格
  2. 声明块的右花括号单独成行,并与该声明块的第一个字符同列
  3. 声明块中每一个声明独占一行
  4. 每个声明前需要缩进(两个空格一tab)
  5. 每条声明语句的 : 后应该插入一个空格
  6. 所有声明语句都应当以分号结尾
  7. 在多个选择器的规则集中,每个单独的选择器独占一行。
  8. 对于只包含一条声明的样式,为了易读性和便于快速编辑,建议将语句放在同一行
  9. 单引号或双引号的选择保持一致, 推荐使用 "" 双引号
/* 多个选择器的规则集 */.link-1,.link-2,.link-3 {  display: block;  width: 100px;  height: 30px;  font-size: 12px;}/* 只包含一条声明的样式 */.link-1 { width: 60px; }.link-2 { width: 140px; }.link-3 { width: 220px; }

属性声明顺序

相关的样式应组合在一起归为一组,并建议按照如下顺序声明:

1. positon2. display && box model3. others
.content {  /* position */  position: absolute;  top: 0;  right: 0;  bottom: 0;  left: 0;  z-index: 10;  /* display and box model */  display: block;  float: right;  width: 100px;  height: 100px;  /* others */  text-align: center;  font: 12px/1.5 tahoma,arial,"Hiragino Sans GB","Microsoft Yahei","\5b8b\4f53";  line-height: 1.5;  color: #333;  background-color: #f5f5f5;  border: 1px solid #e5e5e5;  border-radius: 3px;}

不同的团队有不同的风格喜好,比如有的热衷于按照首字母排序,anyway,只要和团队的风格保持一致即可。

带私有前缀的属性声明顺序

当使用特定厂商的带有前缀的属性时,要注意声明的顺序,标准的 CSS3 属性放最后一个(WHY), 如下:

.rotate {  -webkit-transform: rotate(-3deg);  -moz-transform: rotate(-3deg);  -ms-transform: rotate(-3deg);  transform: rotate(-3deg);}

属性简写

尽可能使用简写属性。常见的可简写的属性如下:

  • font
  • margin
  • padding
  • border
  • background
/* not recommend */.selector {  font-family: palatino, georgia, serif;  font-size: 100%;  line-height: 1.6;  padding-bottom: 2em;  padding-left: 1em;  padding-right: 1em;  padding-top: 0;}
/* recommended */.selector {  border-top: 0;  font: 100%/1.6 palatino, georgia, serif;  padding: 0 1em 2em;}

数字简写

0 和单位

属性值为0时,省略单位

.selector {  margin: 0;  padding: 0;}

大于-1小于1的属性值中的0前缀

这种情况下,省略0

.selector {  padding: .8em;}

16进制颜色值

如可缩写为 3 个字符的颜色值,那么就尽可能使用 3 个字符的 16 进制颜色值。

/* not recommended */color: #334455;
/* recommended */color: #345;


注释

语法

/* 这是个注释 */

注释应当简洁且必要,整体风格保持一致,建议:

  • 尽量保持单行注释,控制注释长度
  • 将注释放在主题上方并独占一行
  • 使用注释将 CSS 代码分割为独立的部分


CSS文件引入

  • 单独的 *.css 文件编码必须使用 utf-8( 无 BOM )
  • 文件一律通过 link 方式引入( NO @import )
  • 当只是单个页面使用时,才使用 <style> 标签

参考

  • http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml
  • http://codeguide.bootcss.com/
  • https://github.com/necolas/idiomatic-css

0 0