码迷,mamicode.com
首页 > Web开发 > 详细

CSS的优先级别

时间:2015-01-27 00:43:08      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

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>

    技术分享




CSS的优先级别

标签:

原文地址:http://my.oschina.net/cobish/blog/371988

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!