海阔凭鱼跃,天高任鸟飞!

天高任鸟飞

       

如何编写兼容多浏览器的CSS代码

作者:     目录: CSS+HTML & PHP+MySQL     发表: 2009年12月18日

一个优秀的网站要尽量兼容所有浏览器,但由于浏览器类型多样(IE 5, IE 6, IE7, IE 8, Firefox, Chrome, Safari),以及浏览器对CSS高版本的支持问题,这就给网页开发者带来诸多困难。

为了降低网页开发者寻找解决方案及编写代码的时间,我们收集了一些方法,以期能缩短开发时间,挺高网页在多浏览器中的兼容性。

IE浏览器兼容性解决方案

通过使用IE中的条件注释 (Conditional comments)。
条件注释只能用于IE 5以后版本的浏览器,其他类型的浏览器将会忽略此注释。
如果你安装了多个IE,条件注释(Conditional comments)将会以最高版本的IE为标准。

条件注释(Conditional comments)示例:

<!--[if IE]>
 <style>
  #logo {
          margin-left: 20px;
        }
</style>
<![endif]-->

条件注释(Conditional comments)说明:

  1. 条件注释的基本结构和HTML的注释(<!-- -->)是一样的。因此IE以外的浏览器将会把它们看作是普通的注释而完全忽略它们。
  2. IE将会根据if条件来判断是否如解析普通的页面内容一样解析条件注释里的内容。
  3. 条件注释使用的是HTML的注释结构,因此他们只能使用在HTML文件里,而不能在CSS文件中使用。

我们来测试一下条件注释(Conditional comments)的实际效果。

代码如下:

<!--[if IE]>
  根据条件判断,这是Internet Explorer<br />
< ![endif]-->
<!--[if IE 5]>
  根据条件判断,这是Internet Explorer 5<br />
< ![endif]-->
<!--[if IE 5.0]>
  根据条件判断,这是Internet Explorer 5.0<br />
< ![endif]-->
<!--[if IE 5.5]>
  根据条件判断,这是Internet Explorer 5.5<br />
< ![endif]-->
<!--[if IE 6]>
  根据条件判断,这是Internet Explorer 6<br />
< ![endif]-->
<!--[if gte IE 5]>
  根据条件判断,这是Internet Explorer 5 或者更高<br />
< ![endif]-->
<!--[if lt IE 6]>
  根据条件判断,这是版小于6的Internet Explorer<br />
< ![endif]-->
<!--[if lte IE 5.5]>
  根据条件判断,这是Internet Explorer 5.5或更低<br />
< ![endif]-->

注:gt代表大于, lte代表小于或等于。

预览 条件注释(Conditional comments)的实际效果

重置CSS各个元素的属性值

由于各个浏览器对CSS元素默认的属性值进行解析时,可能有所差异,所以我们尽量重置所需的CSS元素的属性值(CSS reset styles)。

我们常见如下所示的重置CSS默认属性值的代码:

* { margin: 0; padding: 0; }

但是仅对margin和padding重置也许远远不够,下面的代码对常用的CSS元素进行了重置。

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-weight: inherit;
  font-style: inherit;
  font-size: 100%;
  font-family: inherit;
  vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
  outline: 0;
}
body {
  line-height: 1;
  color: black;
  background: white;
}
ol, ul {
  list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
  border-collapse: separate;
  border-spacing: 0;
}
caption, th, td {
  text-align: left;
  font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: "";
}
blockquote, q {
  quotes: "" "";
}

随着CSS3规范出台,又增加了很多新的元素,CSS3对页面样式的定义功能越来越强大,但众多浏览器对新标准的支持也是一个渐进的过程,我们在编写CSS代码时,尽可能尝试使用新的CSS元素,但要保证在新元素不能发挥作用时,页面样式的变化在我们可承受范围之内。

标签:

14 个评论

  1. SEO培训说道:

    博主用的是什么模板啊?真好看,支持你

    1. 任鸟飞说道:

      嘿嘿,我自己制作的模板。

  2. 流量计说道:

    写的不错,支持,顶一下

  3. 天方夜谭说道:

    非常需要这方面的资料 ,谢谢分享!

回复 SEO培训 取消回复