CSS优化技巧7则

  最近在做项目的后期图片定位、空间布局之类的美工细致活,以前都没什么注意,用到了临时谷哥|度娘一下。在网上找了些CSS的技巧,在此分享。

  CSS是页面效果呈现中非常重要的组成部分,它包括颜色、大小尺寸、背景和字体等。写CSS很简单很容易,但是要想写出精炼的CSS代码还是有很多技巧的。

下面就是技巧7则:

1. 合并多个相同属性

  比如很多人写margin会这样写:

margin-top: 8px;
margin-right: 4px;
margin-bottom: 8px;
margin-left: 4px;

  但是这样写更高效:

margin: 8px 4px 8px 4px;

  对于font、background属性来说,也一样,常规写法:

font-family: Tahoma;
font-weight: bold;
font-style: italic;
font-size: 12px;

  推荐写法:

font: italic bold 12px Tahoma;

  常规写法:

background-image: url(bk_main.jpg);
background-repeat: repeat-x;
background-color: #ccccff;

  推荐写法:

background: #ccccff url(bk_main.jpg) repeat-x;

2. 把具有相同属性的标签写在一块

  比如:

H2
{
font-size
: 16pt;
color
: #4169e1;
font-family
: 'Trebuchet MS' , Arial;
margin
: 4px 0px 2px;
padding-left
: 10px;
text-decoration
: underline;
}

H3
{
font-size
: 14pt;
color
: #4169e1;
font-family
: 'Trebuchet MS' , Arial;
margin
: 4px 0px 2px;
padding-left
: 10px;
text-decoration
: underline;
}

  更好的写法是这样:

H2, H3 
{
  color
: #4169e1;
  font-family
: ‘Trebuchet MS’ , Arial;
  margin
: 4px 0px 2px;
  padding-left
: 10px;
  text-decoration
: underline;
}

H2
{
  font-size
: 16pt;
}

H3
{
  font-size
: 14pt;
}

3. 简化颜色

  比如 #99ff33 可以写成 #9f3

  比如 #ff0000 可以写成 with #f00

  比如 #000000 可以写成 #000

4. 在父级元素中用Class

  比如有这样一段代码:

<p>Home</p>
<p>About</p>
<p>Contact</p>
<p>Sitemap</p>

  其实上面的可以这样写:

<div>
<p>Home</p>
<p>About</p>
<p>Contact</p>
<p>Sitemap</p>
<div>

5. 不要使用令人眼花缭乱的注释

  比如下面这样的:

/*****************************/
/**********Header CSS*********/
/*****************************/

  你可以把它写成这样:

/*Header CSS*/

6. 永远不要在行内元素中加入CSS

<p style=”font-size: 14pt ;font-family: Arial; text-decoration: underline;”>Home</p>
<p style=”font-size: 14pt ;font-family: Arial; text-decoration: underline;”>About</p>
<p style=”font-size: 14pt ;font-family: Arial; text-decoration: underline;”>Contact</p>
<p style=”font-size: 14pt ;font-family: Arial; text-decoration: underline;”>Sitemap</p>

  请把它们写成这样:

<p>Home</p>
<p>About</p>
<p>Contact</p>
<p>Sitemap</p>

7. 移除多余的空格和空行

  移除多余的空格和空行能够减小style文件大小。

原址:http://www.zreading.cn/ican/2011/07/css/

posted on 2011-08-16 16:36  Jackey_Chen  阅读(547)  评论(0编辑  收藏  举报