Home  >  Article  >  Web Front-end  >  CSS的优先级别_html/css_WEB-ITnose

CSS的优先级别_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-21 09:17:581091browse

1、样式的优先级

    内联样式 > 内部样式 > 外部样式

    以下的特例:外部样式会覆盖内部样式(不推荐内联样式)

<html><head>    <style type="text/css">    div { background:red; }    </style>    <link rel="stylesheet" type="text/css" href="style.css" /></head><body>    <div>Hello World!</div></body></html>


2、选择器的优先权

    内联样式(1000)> id(100)> class(10)> tag(10)

    以下例子div将显示的背景色是黑色。

<html><head>    <style type="text/css">    #divId    { height:100px; background:black; }    .divClass { height:100px; background:green; }    </style></head><body>    <div id="divId" class="divClass">Hello World!</div></body></html>

    


    同理,之前遇到过一个问题:

<html><head>    <style type="text/css">    #divId    { height:100px; background:black; }    .divClass { height:100px; background:red; }    </style></head><body>    <div id="divId"></div></body><script type="text/javascript">    window.onload = function() {        var divId = document.getElementById("divId");        divId.className = "divClass";    };</script></html>

    

    这时你会发现js的代码不起作用,相信你应该知道原因了吧。

    解决的方法有很多,以下说说两种:

    (1)如果需要修改的属性少,可以直接用js修改属性

window.onload = function() {    var divId = document.getElementById("divId");    divId.style.background = "red";};

    (2)当要修改的属性多,可以在外出加多一个有id的标签,让class的优先级高于当前div的id

<html><head>    <style type="text/css">    #divId    { height:100px; background:black; }    #boss .divClass { height:100px; background:red; }    </style></head><body>    <div id="boss">        <div id="divId"></div>    </div></body><script type="text/javascript">    window.onload = function() {        var divId = document.getElementById("divId");        divId.className = "divClass";    };</script></html>

    




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn