简体   繁体   English

CSS奇怪的悬停行为

[英]CSS Strange hover behavior

I have a html like this; 我有一个这样的html;

<div id = "header">
        <a href ="#">Panel</a>
        <ul class="headermenu">
            <li><a href="">asdas</a></li>
            <li><a href="">asdasd</a></li>
        </ul>
</div>

and css like this; 像这样的CSS;

*{
    padding:0px;
    margin:0px;
    font-family: "Open Sans",Arial, Verdana;
    font-weight:100;
}

ul{
    list-style-type:none;
    padding:0px;
    margin:0px;
}

div#header{
 margin:40px;   
}

div#header a{
    color:#B2B4B8;
    line-height:40px;
    display:block;
    float:left;
}


.headermenu li{
    float:left;
}

.headermenu li a{
    display:block;
    margin-left:20px;
    font-size:12px;
}

.headermenu li a:hover{
    color:#000;
}

.headermenu{
    float:right;
    margin-right:20px;
}

I could not apply white color to hover of a of ul which has a class named headermenu, using .headermenu li a:hover 我无法使用.headermenu li a:hover将白色应用于ul类的标题为headermenu .headermenu li a:hover

However I can apply this hover using div#header .headermenu li a:hover . 但是我可以使用div#header .headermenu li a:hover来应用此div#header .headermenu li a:hover

WHY? 为什么? The all other syles are applied under .headermenu selector, but hover could not why? 所有其他样式都在.headermenu选择器下应用,但是悬停不能为什么?

JSFiddle JSFiddle

Your div#header a{ is setting the color, and an ID element will always take precedence over any class based element. 您的div#header a{设置颜色,并且ID元素将始终优先于任何基于类的元素。

So your class based hover line, is being ignored. 因此,基于类的悬停线将被忽略。

It's due to selector specificity. 这是由于选择器的特殊性。 Your ID element has higher specificity than the class element and since both of them determine the color of your element, ID takes precedence. 您的ID元素比class元素具有更高的特异性,并且由于它们都决定了元素的颜色,因此ID优先。

More details: http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/ 更多详细信息: http : //www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

I found this very helpful when learning about css rules: http://specificity.keegan.st/ 在学习CSS规则时,我发现这非常有帮助: http : //specificity.keegan.st/

just add !important in your hover css 只需在悬浮式CSS中添加!important

.headermenu li a:hover{ color:#000 !important; .headermenu li a:hover {color:#000!important; } }

or try this: 或尝试以下方法:

div#header .headermenu li a:hover{ color:#000;} div#header .headermenu li a:hover {color:#000;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM