CSS是页面效果呈现中很是重要的组成部分,它包括颜色、大小尺寸、背景和字体等。写CSS很简单很容易,可是要想写出精炼的CSS代码仍是有不少技巧的。
下面就是技巧7则:
1. 合并多个相同属性;
好比不少人写margin会这样写
margin-top: 8px;
margin-right: 4px;
margin-bottom: 8px;
margin-left: 4px;
可是这样写更高效
margin: 8px 4px 8px 4px;
对于font属性来讲,也同样,
常规写法
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文件大小.