日期:2014-05-17  浏览次数:20692 次

CSS技巧让你的网站更上一层楼
47个CSS技巧让你的网站更上一层楼

    CSS是网站的外衣,所谓人靠衣装,佛靠金装,CSS决定了你给用户的第一感觉。虽然一直在做网站的架构和后端开发,但是还是需要多揣点CSS技巧,以防万一。

01.DIV水平居中

DIV 水平居中很简单,只需要设置DIV的宽带以及让左右margins设置成auto:

div#container {width: 960px; margin: 0 auto }

02.文字垂直居中

单行文字居中,只需要将行高和容器高度设置成一样即可。比如下面的HTML代码:

<div id="container">我是一行字</div>

然后通过下面的样式就可以居中:

div#container {height: 35px; line-height: 35px;}

如何你有很多行字,只要将行高设置成容器的高度的1/N就好。
03.DIV垂直居中

比如有以下两个div,如何让包在中间的div垂直居中,这里有一篇详细的介绍文章。

<div id="f">
 <div id="s">Some Things!</div>
</div>

首先,将外层容器的定位为relative。

div#f{ position:relative; height:500px; }

然后,将里面的容器定位设置成absolute,再将它的左上角沿y轴下移50%,最后将它margin-top上移本身高度的50%即可。

div#s { position: absolute; top: 50%; height: 250px; margin-top: -125px; }

使用同样的思路,也可以做出水平居中的效果。
04.自适应宽带的图片

可以通过以下样式实现只适用外层容器大小的图片:

img {max-width: 100%}
/* IE 6 hack */
<!--[if IE 6]>
img {width: 100%}
<![endif]-->

05.3D按钮

要想让按钮具有3D效果,可以将它的左上部边框设为浅色,右下部边框设为深色即可。

div#button {
   background: #888;
   border: 1px solid;
   border-color: #999 #777 #777 #999;
  }

06. CSS Font 缩写

body {
   font-family: Arial, Helvetica, sans-serif;
   font-size: 13px;
   font-weight: normal;
   font-variant: small-caps;
   font-style: italic;
   line-height: 150%;
}
/* 可以缩写成以下这种方式 */
body {
   font: font-style font-variant font-weight font-size/line-height font-family;
}

详细介绍参见:A Primer on the CSS Font Shorthand Property
06.可以在DIV上设置多个class

<div class="class-1 class-2 class-3">content</div>

  class-2 {color: blue} 
  class-3 {color: green} 
  class-1 {color: red}

08.圆角

CSS3中很容易实现圆角:

.element {border-radius: 5px}

但是在CSS3还没全民普及之前我在 Safari, Chrome, 之类 webkit 核心的浏览器中使用 -webkit-border-radius 以及在 Firefox 这些基于 Mozilla 的浏览器使用 -moz-border-radius 来实现圆角。

/* Safari, Chrome */
.element {
   border-radius: 5px
   -webkit-border-radius: 5px
   -moz-border-radius: 5px
}
/* Firefox */
.element {
   border-top-left-radius: 5px
   -webkit-border-top-left-radius: 5px
   -moz-border-radius-top-left
}

至于其他的浏览器可以用JQuery 插件来实现圆角。

$(".element").corner("5px");

09.link 状态的设置顺序

a:link 
a:visited 
a:hover 
a:active

简单记忆法:love hate (LVHA)
10.Clearing and Containing Floats

使用 float 和 clear 设置容器的排序,具体的还是看这篇文章吧。
11.条件注释

条件注释只适用于IE这个杯具的浏览器。

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="ie-stylesheet.css" />
< ![endif]-->
<!--[if IE 6]> - targets IE6 only -->
<!--[if gt IE 6]> - targets IE7 and above -->
<!--[if lt IE 6]> - targets IE5.5 and below -->
<!--[if gte IE 6]> - targets IE6 and above -->
<!--[if lte IE 6]> - targets IE6 and below -->

12.HTML Hack for IE

IE这个杯具的浏览器可以通过以下方式进行 hack 。被hack的css只会运行在特定的浏览器上。

/* the following rules apply only to IE6 */
* html{
}
* html body{
}
* html .foo{
}

/* the following rules apply only to IE7 */
*+html .foo{
}

13.CSS的优先级

基本规则是:行内样式 > id样式 > class样式 > 标签名样式。
14.IE中min-height修正

由于IE6不支持min-height,我们可以通过以下这些方式修正:

/* 方法一 */
.element {
 m