Div+css首页

WEB标准技术学习-CSS样式的优先级问题

css样式的优先级问题
时间: 2007-4-10 21:15:59 浏览:1205 

css中,你可以为同一个标签定义多个样式,如下面的例子:

------------------------------例子----------------------------
<style type="text/css">
<!--
#aaa{
   background-color: Fuchsia;
}
.ab{
   background-color: Black;
}
td{
   background-color: Aqua ;
}
-->
</style>
<table>
<tr>
<td class="ab" id="aaa" style="height:200px;width:200px;background-color: Blue;"></td>
</tr>
</table>
------------------------------------------------------

这么多的样式,哪个是有效的呢?
我们一个一个把上面的样式删除,在浏览器中可以看到:
style的优先级最高,然后是id,再来是class,最后才是td
另外,使用!important可以改变优先级别为最先,如下:

-----------------------------------------
<style type="text/css">
<!--
#aaa{
   background-color: Fuchsia;
}
.ab{
   background-color: Black;
}
td{
   background-color: Aqua !important;
}
-->
</style>
<table>
<tr>
<td class="ab" id="aaa" style="height:200px;width:200px;background-color: Blue;"></td>
</tr>
</table>
------------------------------------------

td将会显示为Aqua
即优先级变为td,然后是style,再来是id,最后是class

 

From: http://forest.blogbus.com/logs/2005/10/1518373.html

 

 

以前写过一篇《关于CSS样式的优先级问题》,当时由于对浏览器的兼容性问题没有太多的了解,所用到的例子也没有提到与浏览器相关的内容,在此做一下补充:

在此要特别提到!important声明,下面还是用以前的那个例子:

-----------------------------------------
<style type="text/css">
<!--
#aaa{
   background-color: Fuchsia;
}
.aaa{
   background-color: Black;
}
td{
   background-color: Aqua !important;
}
-->
</style>
<table>
<tr>
<td class="aaa" id="aaa" style="height:200px;width:200px;background-color: Blue;"></td>
</tr>
</table>
------------------------------------------

td将会显示为Aqua,这在IE4+的浏览器与支持!important声明的都是正确的,但如果换成这下这样:

-----------------------------------------
<style type="text/css">
<!--
#aaa{
   background-color: Fuchsia;
}
.aaa{
   background-color: Black;
}
td{
   background-color: Aqua !important;
   background-color: Green;
}
-->
</style>
<table>
<tr>
<td class="aaa" id="aaa" style="height:200px;width:200px;background-color: Blue;"></td>
</tr>
</table>
------------------------------------------

这个例子的结果是在IE4+的浏览器中td的颜色为Blue,而在FF中的颜色为Aqua 。这说明了在IE4+浏览器中的!important声明并不是“真正的提高优先级”,或说是“不完全的声明”,在声明之后如果有新的、相同属性名的定义,!important声明将会失效。而在FF中,!important声明在同个样式类中的优先级始终是最高的。

因此,当要修正IE与FF中的差异时,就可以使用第二个例子中的做法,大多数是用于修正定位的问题。


 

From: http://forest.blogbus.com/logs/2006/03/2026348.html

Div之家