编程小贴士

给你的编程提供小点子


编写高效整洁CSS代码的13个建议

CSS学起来并不难,但在大型项目中,就变得难以管理,特别是不同的人在CSS书写风格上稍有不同,团队上就更加难以沟通,为此总结了一些如何实现高效整洁的CSS代码原则:

1. 使用Reset但并非全局Reset

  不同浏览器元素的默认属性有所不同,使用Reset可重置浏览器元素的一些默认属性,以达到浏览器的兼容。但需要注意的是,请不要使用全局Reset:

*{ margin:0; padding:0; }

这不仅仅因为它是缓慢和低效率的方法,而且还会导致一些不必要的元素也重置了外边距和内边距。在此建议参考YUI Reset和Eric Meyer的做法。我跟Eric Meyer的观点相同,Reset并不是一成不变的,具体还需要根据项目的不同需求做适当的修改,以达到浏览器的兼容和操作上的便利性。我使用的Reset如下:

/** 清除内外边距 **/
body, h1, h2, h3, h4, h5, h6, hr, p,
blockquote, /* structural elements 结构元素 */
dl, dt, dd, ul, ol, li, /* list elements 列表元素 */
pre, /* text formatting elements 文本格式元素 */
form, fieldset, legend, button, input, textarea, /* form elements 表单元素 */
th, td, /* table elements 表格元素 */
img/* img elements 图片元素 */{
  border:medium none;
  margin: 0;
  padding: 0;
}
/** 设置默认字体 **/
body,button, input, select, textarea {
  font: 12px/1.5 '宋体',tahoma, Srial, helvetica, sans-serif;
}
h1, h2, h3, h4, h5, h6 { font-size: 100%; }
em{font-style:normal;}
/** 重置列表元素 **/
ul, ol { list-style: none; }
/** 重置超链接元素 **/
a { text-decoration: none; color:#333;}
a:hover { text-decoration: underline; color:#F40; }
/** 重置图片元素 **/
img{ border:0px;}
/** 重置表格元素 **/
table { border-collapse: collapse; border-spacing: 0; }

2. 良好的命名习惯

  无疑乱七八糟或者无语义命名的代码,谁看了都会抓狂。就像这样的代码:

.aaabb{margin:2px;color:red;}

我想即使是初学者,也不至于会在实际项目中如此命名一个class,但有没有想过这样的代码同样是很有问题的:

<h1>My name is <span class="red blod">Wiky</span></h1>

问题在于如果你需要把所有原本红色的字体改成蓝色,那修改后就样式就会变成:

.red{color:bule;}

这样的命名就会很让人费解,同样的命名为.leftBar的侧边栏如果需要修改成右侧边栏也会很麻烦。所以,请不要使用元素的特性(颜色,位 置,大小等)来命名一个class或id,您可以选择意义的命名 如:#navigation{…},.sidebar{…},.postwrap{…}

这样,无论你如何修改定义这些class或id的样式,都不影响它跟HTML元素间的联系。

另外还有一种情况,一些固定的样式,定义后就不会修改的了,那你命名时就不用担忧刚刚说的那种情况,如

.alignleft{float:left;margin-right:20px;}
.alignright{float:right;text-align:right;margin-left:20px;}
.clear{clear:both;text-indent:-9999px;}

那么对于这样一个段落

<p class="alignleft">我是一个段落!</p>

如果需要把这个段落由原先的左对齐修改为右对齐,那么只需要修改它的className就为alignright就可以了。

3. 代码缩写

  CSS代码缩写可以提高你写代码的速度,精简你的代码量。在CSS里面有不少可以缩写的属性,包括margin,padding,border,font,background和颜色值等,如果您学会了代码缩写,原本这样的代码:

li{
    font-family:Arial, Helvetica, sans-serif;
    font-size: 1.2em;
    line-height: 1.4em;
    padding-top:5px;
    padding-bottom:10px;
    padding-left:5px;
}

就可以缩写为:

li{
    font: 1.2em/1.4em Arial, Helvetica, sans-serif;
    padding:5px 0 10px 5px;
}

如果您想更了解这些属性要怎么缩写,可以参考《常用CSS缩写语法总结》或者下载CSS-Shorthand-Cheat-Sheet.pdf 。

4. 利用CSS继承

  如果页面中父元素的多个子元素使用相同的样式,那最好把他们相同的样式定义在其父元素上,让它们继承这些CSS样式。这样你可以很好的维护你的代码,并且还可以减少代码量。那么本来这样的代码:

#container li{ font-family:Georgia, serif; }
#container p{ font-family:Georgia, serif; }
#container h1{font-family:Georgia, serif; }

就可以简写成:

#container{ font-family:Georgia, serif; }

5. 使用多重选择器

  你可以合并多个CSS选择器为一个,如果他们有共同的样式的话。这样做不但代码简洁且可为你节省时间和空间。如:

h1{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
h2{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }

可以合并为

h1, h2, h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }

6. 适当的代码注释

代码注释可以让别人更容易读懂你的代码,且合理的组织代码注释,可使得结构更加清晰。你可以选择做的样式表的开始添加目录:

/*------------------------------------
    1. Reset
    2. Header
    3. Content
    4. SideBar
    5. Footer
  ----------------------------------- */

如此你代码的结构就一目了然,你可以容易的查找和修改代码。

而对于代码的主内容,也应适当的加以划分,甚至在有必要的地方在对代码加以注释说明,这样也有利于团队开发:

/***    Header  ***/
#header{ height:145px; position:relative; }
#header h1{ width:324px; margin:45px 0 0 20px; float:leftheight:72px;}
 
/***    Content ***/
#content{ background:#fff; width:650px; float:left; min-height:600px; overflow:hidden;}
#content h1{color:#F00}/* 设置字体颜色 */
#content .posts{ overflow:hidden; }
#content .recent{ margin-bottom:20px; border-bottom:1px solid #f3f3f3; position:relative; overflow:hidden; }
 
/***    Footer  ***/
#footer{ clear:both; padding:50px 5px 0; overflow:hidden;}
#footer h4{ color:#b99d7f; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; }

7. 给你的CSS代码排序

如果代码中的属性都能按照字母排序,那查找修改的时候就能更加快速:

/*** 样式属性按字母排序 ***/
div{
    background-color:#3399cc;
    color:#666;
    font:1.2em/1.4em Arial, Helvetica, sans-serif;
    height:300px;
    margin:10px 5px;
    padding:5px 0 10px 5px;
    width:30%;
    z-index:10;
}

8. 保持CSS的可读性

  书写可读的CSS将会使得更容易查找和修改样式。对于以下两种情况,哪种可读性更高,我想不言而明。

/*** 每个样式属性写一行 ***/
div{
    background-color:#3399cc;
    color:#666;
    font: 1.2em/1.4em Arial, Helvetica, sans-serif;
    height:300px;
    margin:10px 5px;
    padding:5px 0 10px 5px;
    width:30%;
    z-index:10;
}
 
/*** 所有的样式属性写在同一行 ***/
div{ background-color:#3399cc; color:#666; font: 1.2em/1.4em Arial, Helvetica, sans-serifheight:300px; margin:10px 5px; padding:5px 0 10px 5px; width:30%; z-index:10; }

当对于一些样式属性较少的选择器,我会写到一行:

/*** 选择器属性少的写在同一行 ***/
div{ background-color:#3399cc; color:#666;}

对于这个规则并非硬性规定,但无论您采用哪种写法,我的建议是始终保持代码一致。属性多的分行写,属性少于3个可以写一行。

9. 选择更优的样式属性值

  CSS中有些属性采用不同的属性值,虽然达到的效果差不多,当性能上却存在着差异,如

区别在于border:0把border设为0px,虽然在页面上看不见,但按border默认值理解,浏览器依然对border-width/border-color进行了渲染,即已经占用了内存值。
而border:none把border设为“none”即没有,浏览器解析“none”时将不作出渲染动作,即不会消耗内存值。所以建议使用border:none;

同样的,display:none隐藏对象浏览器不作渲染,不占用内存。而visibility:hidden则会。

10. 使用<link>代替@import

首先,@import不属于XHTML标签,也不是Web标准的一部分,它对于较早期的浏览器兼容也不高,并且对于网站的性能有某些负面的影响。具体可以参考《高性能网站设计:不要使用@import》。所以,请避免使用@import

11. 使用外部样式表

   这个原则始终是一个很好的设计实践。不单可以更易于维护修改,更重要的是使用外部文件可以提高页面速度,因为CSS文件都能在浏览器中产生缓存。内置在 HTML文档中的CSS则会在每次请求中随HTML文档重新下载。所以,在实际应用中,没有必要把CSS代码内置在HTML文档中:

<style type="text/css" >
    #container{ .. }
    #sidebar{ .. }
</style>
 
 
<li style="font-family:Arial, helvetica, sans-serif; color:#666; " >

而是使用<link>导入外部样式表:

<link rel="stylesheet" type="text/css" href="css/styles.css" />

12. 避免使用CSS表达式(Expression)

  CSS表达式是动态设置CSS属性的强大(但危险)方法。Internet Explorer从第5个版本开始支持CSS表达式。下面的例子中,使用CSS表达式可以实现隔一个小时切换一次背景颜色:

background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00" );

如上所示,expression中使用了JavaScript表达式。CSS属性根据JavaScript表达式的计算结果来设置。

表达式的问题就在于它的计算频率要比我们想象的多。不仅仅是在页面显示和缩放时,就是在页面滚动、乃至移动鼠标时都会要重新计算一次。给CSS表达式增加一个计数器可以跟踪表达式的计算频率。在页面中随便移动鼠标都可以轻松达到10000次以上的计算量。

如果必须使用CSS表达式,一定要记住它们要计算成千上万次并且可能会对你页面的性能产生影响。所以,在非不得已,请避免使用CSS表达式。

13. 代码压缩

  当你决定把网站项目部署到网络上,那你就要考虑对CSS进行压缩,出去注释和空格,以使得网页加载得更快。压缩您的代码,可以采用一些工具,如YUI Compressor

利用它可精简CSS代码,减少文件大小,以获得更高的加载速度。

 

107 Responses to “ 编写高效整洁CSS代码的13个建议 ”

  1. me suba说道:

    2yhwAG I really liked your blog.Really looking forward to read more. Awesome.

  2. This website was how do I say it? Relevant!! Finally I have found something that helped me. Thanks!

  3. painting说道:

    to learn the other and this kind of courting is considerably extra fair and passionate. You could incredibly really effortlessly locate a

  4. Lung Health说道:

    Sweet web site , super design and style , really clean and utilize friendly.

  5. who had been conducting a little homework on this. And he in

  6. Really enjoyed this post.Thanks Again. Will read on

  7. Oluwadamilare说道:

    Wow! This can be one particular of the most useful blogs We have ever arrive across on this subject. Actually Magnificent. I am also an expert in this topic therefore I can understand your hard work.

  8. It as not that I want to duplicate your web-site, but I really like the design and style. Could you tell me which design are you using? Or was it tailor made?

  9. click说道:

    There as definately a great deal to find out about this issue. I like all the points you have made.

  10. It as hard to find knowledgeable people on this topic, however, you seem like you know what you are talking about! Thanks

  11. ugg australia bailey button boot bomber jacket chestnut

  12. You made some clear points there. I looked on the internet for the subject and found most guys will consent with your site.

  13. You can certainly see your enthusiasm in the work you write. The arena hopes for even more passionate writers such as you who are not afraid to say how they believe. At all times follow your heart.

  14. It as not that I want to replicate your web page, but I really like the layout. Could you tell me which theme are you using? Or was it especially designed?

  15. Just my opinion, it might make your posts a little bit more interesting.

  16. private Hire说道:

    Way cool! Some extremely valid points! I appreciate you writing this post plus the rest of the site is very good.

  17. gia sat thep说道:

    Some really excellent info , Gladiolus I observed this.

  18. gia sat thep说道:

    This is a really great study for me, Ought to admit that you just are a single of the best bloggers I ever saw.Thanks for posting this informative post.

  19. visit说道:

    Streaming gratuit erotique you por no Feel free to visit my web site; sexe shop

  20. Very informative blog post. Really Cool.

  21. Just Browsing While I was surfing yesterday I noticed a excellent article concerning

  22. Citizenship说道:

    I reckon something truly special in this internet site.

  23. this说道:

    I think this is a real great article.Really looking forward to read more. Much obliged.

  24. Nwokolo说道:

    Thanks so much for the blog.Really looking forward to read more. Will read on

  25. trang tri noel说道:

    Very good article.Thanks Again. Keep writing.

  26. klm coupon code说道:

    Thanks again for the blog post.Really looking forward to read more. Great.

  27. magnificent post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I am sure, you have a great readers a base already!

  28. your blog posts. After all I all be subscribing for your feed and I am hoping you write again very soon!

  29. Very fantastic info can be found on website.

  30. metal recycling说道:

    Wow that was unusual. I just wrote an really long comment but after I clicked submit my comment didn at show up. Grrrr well I am not writing all that over again. Anyway, just wanted to say great blog!

  31. Say, you got a nice blog.Really thank you! Really Cool.

  32. browse说道:

    You could certainly see your enthusiasm in the paintings you write. The arena hopes for more passionate writers like you who aren at afraid to mention how they believe. All the time follow your heart.

  33. Seriously, such a important online site.|

  34. Thank you, I ave recently been searching for information about this topic for ages and yours is the greatest I ave discovered till now. But, what about the bottom line? Are you sure about the source?

  35. My brother suggested I might like this website. He was totally right. This post actually made my day. You cann at imagine just how much time I had spent for this info! Thanks!

  36. Really informative blog post.Really looking forward to read more. Cool.

  37. online loans说道:

    This can be exactly what I had been searching for, thanks

  38. credits online说道:

    I wish my site loaded up as fast as yours lol

  39. wonderful points altogether, you simply gained a new reader. What would you suggest in regards to your post that you made a few days ago? Any positive?

  40. Emmanuel Ekanem说道:

    I think other website proprietors should take this site as an model, very clean and great user friendly style and design, let alone the content. You are an expert in this topic!

  41. fitness说道:

    This excellent website certainly has all of the information I needed about this subject and didn at know who to ask.

  42. I value the article post.Much thanks again. Really Cool.

  43. You might be my role models. Many thanks to the write-up

  44. check this out说道:

    It as fantastic that you are getting ideas from this post as well as from our argument made at this place.

  45. Wow, great blog article.Thanks Again. Want more.

  46. click here说道:

    Really appreciate you sharing this article.Really looking forward to read more. Great.

  47. It is not my first time to pay a quick visit this site,

  48. It as actually a wonderful and handy section of data. Now i am satisfied that you choose to discussed this useful details about. Remember to stop us educated like this. Many thanks for revealing.

  49. Tejidos说道:

    Very nice article and right to the point. I am not sure if this is actually the best place to ask but do you people have any ideea where to get some professional writers? Thanks

  50. Crochet basico说道:

    Thank you ever so for you blog post.Really looking forward to read more. Really Cool.

  51. try this说道:

    you have an excellent blog right here! would you wish to make some invite posts on my weblog?

  52. blue nike说道:

    You actually make it appear so easy together with your presentation however I in finding this

  53. more说道:

    Thanks for the blog.Much thanks again. Awesome.

  54. free cams说道:

    You will discover some interesting points in time in this article but I do not know if I see all of them center to heart.

  55. It’а†s truly a great and useful piece of info. I am happy that you just shared this helpful information with us. Please stay us informed like this. Thank you for sharing.

  56. School admission说道:

    Perfectly written content material, Really enjoyed reading through.

  57. School admission说道:

    Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, as well as the content!. Thanks For Your article about sex.

  58. ark ps4 server说道:

    My brother suggested I might like this blog. He was entirely right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  59. niw说道:

    to go to see the web site, that as what this web page is providing.

  60. visit website说道:

    Perfectly written content, Really enjoyed reading through.

  61. Only a smiling visitor here to share the love (:, btw great design and style.

  62. I truly appreciate this blog post. Cool.

  63. to learn more说道:

    provide credit and sources back to your site? My website is in the very same niche as

  64. i wish for enjoyment, since this this web page conations genuinely fastidious funny data too.

  65. Terrific article. I am just expecting a lot more. You happen to be this kind of good creator.

  66. This is one awesome article.Thanks Again. Awesome.

  67. scary maze说道:

    Thanks-a-mundo for the article post.Really thank you! Fantastic.

  68. that will be the finish of this write-up. Here you

  69. your presentation however I find this topic to be really one thing

  70. Very nice article. I absolutely love this website. Thanks!

  71. Im no pro, but I believe you just made the best point. You definitely comprehend what youre talking about, and I can actually get behind that. Thanks for being so upfront and so sincere.

  72. Onyekachi说道:

    This blog is really entertaining as well as informative. I have discovered helluva handy tips out of this blog. I ad love to visit it again and again. Thanks a bunch!

  73. That is really fascinating, You are a very skilled blogger.

  74. I really liked your article post.Really thank you! Really Cool.

  75. You made some good points there. I looked on the internet for the subject matter and found most guys will approve with your site.

  76. My brother recommended I might like this blog. He was totally right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  77. You ave made some good points there. I looked on the internet for additional information about the issue and found most individuals will go along with your views on this website.

  78. Thank you for your blog article.Thanks Again. Cool.

  79. Thank you for your blog article.Much thanks again. Want more.

  80. dclm devotionals说道:

    This is a very good tip particularly to those fresh to the blogosphere. Brief but very precise info Many thanks for sharing this one. A must read article!

  81. official site说道:

    I?ve recently started a website, the information you provide on this site has helped me tremendously. Thank you for all of your time & work.

  82. have a look at说道:

    Whats up. Very nice site!! Man.. Excellent.. Amazing.. I all bookmark your blog and take the feeds alsoI am glad to find a lot of useful information right here in the article. Thanks for sharing..

  83. Cathey说道:

    This blog is definitely cool and also informative. I have chosen a lot of useful things out of it. I ad love to go back again soon. Thanks a lot!

  84. Thanks-a-mundo for the article post.Really thank you! Keep writing.

  85. click here说道:

    Really informative article post.Thanks Again. Great.

  86. Merely a smiling visitant here to share the love (:, btw great style and design.

  87. this website说道:

    three triple credit report How hard is it to write a wordpress theme to fit into an existing site?

  88. for details说道:

    Really appreciate you sharing this blog post.Much thanks again. Great.

  89. Your style is very unique in comparison to other folks I have read stuff from. Many thanks for posting when you have the opportunity, Guess I will just book mark this web site.

  90. Share说道:

    some truly interesting points you have written.

  91. miller electric说道:

    Thanks so much for the blog article.Much thanks again. Want more.

  92. Outstanding post, you have pointed out some great points, I too conceive this s a very great website.

  93. you can check说道:

    Im no pro, but I imagine you just crafted the best point. You definitely know what youre talking about, and I can really get behind that. Thanks for staying so upfront and so sincere.

  94. Thanks so much for the article.Much thanks again. Cool.

  95. Thankyou for this post, I am a big big fan of this website would like to proceed updated.

  96. What would you like to see out of a creative writing short story?

  97. click说道:

    I think this is a real great post.Really thank you! Much obliged.

  98. Nikole说道:

    This particular blog is without a doubt awesome and also amusing. I have found a lot of interesting stuff out of it. I ad love to visit it again soon. Thanks!

  99. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is wonderful, as well as the content!

  100. This is really interesting, You are a very skilled blogger. I ave joined your feed and look forward to seeking more of your great post. Also, I ave shared your website in my social networks!

  101. launchpad mk2说道:

    Simply wanna comment that you have a very decent web site , I the style it really stands out.

  102. There is visibly a bundle to identify about this. I think you made some nice points in features also.

  103. Major thankies for the blog article.Much thanks again. Cool.

  104. other details说道:

    It’а†s actually a nice and helpful piece of information. I am happy that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  105. Weird , this post turns up with a dark color to it, what shade is the primary color on your web site?

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>