关于CSS样式的优先级问题

Ghostzhang 发表于

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

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

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

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

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

注:谢谢QQ48251710的朋友指出了文章中的一个错误,现已经改正。

讨论