这里总结的CSS技巧,对前端工程师有很大的帮助,虽然这些技巧都很基本,但如果你或你的团队还不太了解或还没开始使用,可以参考下面文章介绍的内容。 1. 用 firebug 或 console 来调试 在 Firefox 还没有推出 Developer Tools 时,大家一定是用 Firebug 来调试,2006 年 Firebug 第一版 release 出来,让 web 开发者可以更快速的了解网站调试,也可以通过 Firebug 来了解网站的性能。但是现今,Firefox 推出了自家 Developer Tools,而Chrome 也是有很多好用的 技巧 及强大的 Workspace,对 Workspace 不熟悉的,可以参考原文作者文章:Coding on workspace of Chrome Developer tools。 2. Float 或 Inline-Block css 先来看看范例1,中间有三个 column,分别用 float: left 方式来排列:
<div class="wrapper"> <div class="column">test</div> <div class="column">test</div> <div class="column">test</div> </div> CSS 写法:
.wrapper { width: 400px; min-height: 50px; background-color: red; } .column { float: left; width: 100px; height: 100px; background-color: blue; margin-left: 20px; } 会发现背景红色 .wrapper 区块被砍了一半,原因就是没使用 clear: both,正确解法请看范例2,如果不是用此解法,也可以将 float 取代成 display: inline-block,解法请看范例3。上述两种解法是最常见的,终极解法可以通过 pseudo-class :after 来解决此问题。 3. 用 CSS animation 取代 Javascript 原文作者写了一篇 CSS3 Transitions to replace JavaScript animations 文章,就是要告诉前端工程师尽可能将原本使用的 jQuery animation 取代成 CSS 作法,原因在于 CSS animation 的性能远大于 JavaScript Native Language 性能,请参考http://www./ 网站。 4. Form 表单请使用 Label input 上面的例子,只要点选 Name 或 Email 会发现浏览器光标自然会移动到 text input 字段上,设置方式很简单,只要将 label 的 for attribute 设置为 input id 即可:
<label for="username">Name:</label><input type="text" id="username" /> <label for="email">Email:</label><input type="text" id="email" /> 5. 性能:Spiriting everything 每个网站一定会有很多小 icon 图,不管是直接使用在 html 或者是写在 CSS 内,在网络传输的时候,如果 10 张 icon 就会建立 10 条 connection,然而 css_spite 就是解决了此问题,将所有的小图集结成一张大图,通过 css 设置来减少网络连接数,网络上很多工具来达成此目的,像是 CSS Sprite Generator,如果熟悉 Compass 工具,可以直接使用 Spriting with Compass:
.my-icons-sprite, .my-icons-delete, .my-icons-edit, .my-icons-new, .my-icons-save { background: url('/images/my-icons-s34fe0604ab.png') no-repeat; } .my-icons-delete { background-position: 0 0; } .my-icons-edit { background-position: 0 -32px; } .my-icons-new { background-position: 0 -64px; } .my-icons-save { background-position: 0 -96px; } 6. 不要直接修改 image width 和 height 属性 这点其实蛮重要的,现在网站架构的瓶颈,说实在的 80% 以上都是在读取图片文件,有时候 UI 设计师切出一张大图,前端工程师拿去使用,结果图文件很大,工程师就直接通过 css width height 修改图片大小,这样看起来是没问题,但是网站就开始很慢,使用者开始不爽,网站自然就不会有人继续用。正确方式就是将 image resize 成各种版本,可以直接参考这篇 Tools for image optimization:
这招其实还蛮好用的,我们先来看看例子: 我们看到这张图本来的比例大小为宽 228 高 320,但是经过下面 CSS 语法
img { width: 228px; height: 228px; } 图片就变成上述的例子,但是如果我们把 CSS 改成底下呢:
img { max-width: 228px; max-height: 228px; } 出来的结果就是: 8. 善用 :before 和 :after 在前面有提到 float: left 后要加上一个 element clear: both 现在我们可以通过 :after 来解决这问题(示例地址):
.wrapper:after { content: ' '; clear:both; display:block; } 9. 减少 CSS 程序代码 这部份就是减少不必要的程序代码
.class { margin-top:5px; margin-right:10px; margin-bottom:15px; margin-left:20px; } 可以写成
.class { margin:5px 10px 15px 20px; } CSS color 部分 #RRGGBB 可以写成 #RGB 10. 使用 SASS 或 Compass 团队内尚未使用 SASS 或 Compass 吗?个人建议尽快使用这两套工具,还不熟悉这两套工具,建议将底下幻灯片看完: 原文: KidsIL Blog / 编译:wu-boy |
|