使用background和background-image对CSS优先级造成影响

在写一个关于背景图的CSS时候发现一个奇怪的现象,

原图:theme

如下代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>首页 | shopping</title>
    <style type="text/css">
    *{margin: 0;padding: 0;}
    li{list-style-type: none;}
        /*皮肤设置*/
        #skin{width: 115px;height: 15px;margin-top: 12px;float: left;margin-left: 10px;overflow: hidden;text-indent: -999px}
        #skin li{width: 15px;height: 15px;background: url(//images0.cnblogs.com/blog/607355/201408/011822379465492.gif);float: left;cursor:pointer; margin-right:5px;}
        #skin_0{background-position: 0px 0px;}
        #skin_1{background-position: 15px 0px;}
        #skin_2{background-position: 35px 0px;}
        #skin_3{background-position: 55px 0px;}
        #skin_4{background-position: 75px 0px;}
        #skin_5{background-position: 95px 0px;}

    </style>
</head>
<body>
    <ul id="skin">
        <li id="skin_0" class="skin_selected"></li>
        <li id="skin_1">绿</li>
        <li id="skin_2"></li>
        <li id="skin_3">湛蓝</li>
        <li id="skin_4"></li>
        <li id="skin_5"></li>
    </ul>
</body>
</html>

 

理论上效果应该是这样的:image

但是,若其中的 #skin li中背景属性写为 background:   ,则不能实现,结果是这样的image

也就是说,#skin_0、#skin_1、#skin_2、#skin_3、#skin_4、#skin_5这几个id所定义的样式没起作用,还是上面的“#skin li”所定义的 background: url(http://9.liulong.sinaapp.com/theme.gif); 在起作用。

在firebug中也可以看出:image

 

经过我的测试,解决这个问题有两种方式:

第一种是,改为:background-image: url(http://9.liulong.sinaapp.com/theme.gif);则可以实现。

第二种是,把#skin_0,改为#skin li#skin_0 ,其他的依次类推,例如我们更改为:

        #skin li#skin_0{background-position: 0px 0px;}
        #skin li#skin_1{background-position: 15px 0px;}
        #skin li#skin_2{background-position: 35px 0px;}
        #skin_3{background-position: 55px 0px;}
        #skin_4{background-position: 75px 0px;}
        #skin_5{background-position: 95px 0px;}

效果:image

可以看出来,前三个id发生了作用。

综上,我认为使用background和background-image会对CSS优先级造成影响。那么,其他类似的属性应该也是如此,例如使用background和background-color等等这类属性。此处暂时不做验证。

在书写的时候应该注意。CSS选择器写的更细致,要么单使用一个属性定义。

posted @ 2014-08-01 18:23  iulo  阅读(5105)  评论(0编辑  收藏  举报