我们应当尽量减少css样式代码的编写量,代码缩写是很有必要的。这样可以使用户访问你的网页的时候占用更少的带宽。
1.盒模型代码缩写
在将盒模型时,我们讲过盒模型的外边距(margin)、内边距(padding)和边框(border)设置上下左右四个方向的边距是按照顺时针方向设置的:上右下左。如:
margin:10px 15px 12px 14px;/*上设置为10px、右设置为15px、下设置为12px、左设置为14px*/
盒模型代码缩写方法通常有以下三种方法:
(1).如果top、right、bottom、left的值相同,如下面代码:
margin:10px 10px 10px 10px;
可缩写为:
margin:10px ;
(2).如果top和bottom值相同、left和 right的值相同,如下面代码:
margin:10px 20px 10px 20px;
可缩写为:
margin:10px 20px;
(3).、如果left和right的值相同,如下面代码:
margin:10px 20px 30px 20px;
可缩写为:
margin:10px 20px 30px;
注意:padding、border的缩写方法和margin是一致的。
2.颜色值缩写
当你设置的颜色是16进制时,如果每两位数值相同,你可以简写一半。如:
p{color:#000000;} p{color: #336699;}
可简写为:
p{color:#000} p{color:#369}
3.字体缩写
字体的CSS样式同样可以简写,如:
body{ font-style:italic; font-variant:small-caps; font-weight:bold; font-size:12px; line-height:1.5em; font-family:"宋体",sans-serif; }
以上代码可缩写为:
body{ font:italic small-caps bold 12px/1.5em "宋体",sans-serif; }
注意:
(1)、使用这一简写方式你至少要指定 font-size (字号)和 font-family (字体)属性,其他的属性(如 font-weight、font-style、font-variant、line-height)如未指定将自动使用默认值。
(2)、在缩写时 font-size 与 line-height(行间距) 中间要加入“/”斜扛。