一直以来,书写 css 都是率性所为,没有遵循一定的规范;俗话说:没有规矩,不成方圆。造成了代码可读性极差,导致了网站后期维护非常困难。
# 一、书写顺序
| 属性 | |
|---|---|
| 定位 | position z-index display left right top bottom clip | 
| 尺寸 | width height min-height max-height min-width max-width | 
| 文字 | color font-size letter-spacing, color- text-align 等 | 
| 背景 | background-image border 等 | 
| 其他 | animation, transition 等 | 
| /* bad */ | |
| .example { | |
| color: red; | |
| z-index: -1; | |
| background-color: #9e0; | |
| display: inline-block; | |
| font-size: 1.5em; | |
| } | |
| /* good */ | |
| .example { | |
| z-index: -1; | |
| display: inline-block; | |
| font-size: 1.5em; | |
| background-color: #9e0; | |
| } | 
# 二、一些注意事项
# 能缩写的尽量缩写
例如: background-color:#333;background-image: url(skin/p_103x196_1.jpg); background-repeat: repeat-x;
改为: background:url(skin/p_103x196_1.jpg) repeat-x #333;
| /* bad */ | |
| .example { | |
| border-top-style: none; | |
| font-family: serif; | |
| font-size: 100%; | |
| line-height: 1.6; | |
| padding-bottom: 2em; | |
| padding-left: 1em; | |
| padding-right: 1em; | |
| paddiing-top: 0; | |
| } | |
| /* good */ | |
| .example { | |
| border-top: 0; | |
| font: 100%/1.6 serif; | |
| padding: 0 1em 2em; | |
| } | 
# 能少些尽量少写
例如: font-size:0.9em 可以写为: font-size:.9em
# 灰度值可以缩写的缩写
例如: color:#666666; 可以写为: color:#666;
# 在别人阅读代码可以看得多的情况下缩写
例如: navigation 可以写为 nav
# 不建议使用 _ 下划线来命名 CSS 选择器
原因:
- 输入的时候少按一个 shift 键
- 浏览器兼容问题 (比如炼独使用 _tips的选择器命名,在 IE6 是无效的)
- 能良好区分 JavaScript 变量命名 (JS 变量命名是用 _)
# 二、CSS 命名规范 (常用的 CSS 命名规则)
| 名称 | 命名 | 
|---|---|
| 头 | header | 
| 内容 | content/container | 
| 尾 | footer | 
| 导航 | nav | 
| 侧栏 | sidebar | 
| 栏目 | column | 
| 页面外围控制整体佈局宽度 | wrapper | 
| 左右中 | left right center | 
| 登录条 | loginbar | 
| 标志 | logo | 
| 广告 | banner | 
| 页面主体 | main | 
| 热点 | hot | 
| 新闻 | news | 
| 下载 | download | 
| 子导航 | subnav | 
| 菜单 | menu | 
| 子菜单 | submenu | 
| 搜索 | search | 
| 友情链接 | friendlink | 
| 页脚 | footer | 
| 版权 | copyright | 
| 滚动 | scroll | 
| 内容 | content | 
| 标签 | tags | 
| 文章列表 | list | 
| 提示信息 | msg | 
| 小技巧 | tips | 
| 栏目标题 | title | 
| 加入 | joinus | 
| 指南 | guide | 
| 服务 | service | 
| 注册 | regsiter | 
| 状态 | status | 
| 投票 | vote | 
| 合作伙伴 | partner | 
# 三、css 文件中注释的写法
# 注释的写法
| /* Header */ | |
| 内容区 | |
| /* End Header */ | 
# ID 的命名
| 页面结构 | 命名 | 
|---|---|
| 容器 | container | 
| 页头 | header | 
| 内容 | content/container | 
| 页面主体 | main | 
| 页尾 | footer | 
| 导航 | nav | 
| 侧栏 | sidebar | 
| 栏目 | column | 
| 页面外围控制整体佈局宽度 | wrapper | 
| 左右中 | left right center | 
# CSS 样式表文件命名
| 主要的 | master.css | 
| 模块 | module.css | 
| 基本共用 | base.css | 
| 版面 | layout.css | 
| 主题 | themes.css | 
| 专栏 | columns.css | 
| 文字 | font.css | 
| 表单 | forms.css | 
| 补丁 | mend.css | 
| 打印 | print.css | 
