a:hover color is not working

2019-06-21 18:37发布

问题:

a very strange thing..

I want to change the text color and background color of the links when hovered.

this is the code

css:

#link-menu a
{
    color:white;
    display:block;
    height:100%;
    width: 100%;
    text-decoration:none;
    text-align:center;
    line-height:45px;
    font-weight:bold;
    font-family:"trebuchet ms","comic sans ms";
    outline:none;
}

.link2 a:hover 
{
    color:black;
    background:white;
}

its not that the hover is not working. background color is changing but the text color is not changing.

one more imortant fact is that if instead of using the class .link2 , i use an id, color also changes. The issue is with using class only. Can somebody please explain the reason and the solution?

Note: i dont want to use the parent element id. because i dont want to change background of all links.

回答1:

Its a specificity issue; your first selector is overriding the second because it has an ID. Your only option is using an !important rule or including the parent as an ancestor in your second selector so its more specific, e.g.

#link-menu a:hover {
    background: white;
    color: black;
}


回答2:

#link-menu a

Has higher priority. You need to increase priority of the second selector. Try adding !important

.link2 a:hover 
{
    color:black !important;
    background:white;
}


回答3:

#link-menu a is more specific than .link2 a:hover, because the first one includes an ID and the second one doesn't.

Therefore, it overrides properties in the second rule.

To fix this, change them so they both have the same specificity (before the :hover), or add !important.