• [原] 关于CSS样式的优先级问题

    2005-10-19

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://forest.blogbus.com/logs/1518373.html

    在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

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


    收藏到:Del.icio.us