基于类设置一个: 悬停

我有以下 HTML:

<div class="menu">
<a class="main-nav-item" href="home">home</a>
<a class="main-nav-item-current" href="business">business</a>
<a class="main-nav-item" href="about-me">about me</a>
</div>

在 CSS 中,我想将这些菜单项的 a:hover设置为特定的颜色,所以我写道:

.menu a:hover
{
color:#DDD;
}

但是,我想设置这个 a:hover颜色只对那些 <a>类标签 主导航装置,而不是 主导航项目目前,因为它有一个不同的颜色,不应该改变悬停。除了 目前类之外,菜单 div 中的所有 <a>标签在悬停时都应该改变颜色。

我如何使用 CSS 做到这一点?

我试过

.menu a:hover .main-nav-item
{
color:#DDD;
}

认为只有具有主导航项目类的才会在悬停时改变颜色,而不会改变当前的颜色。但是没有用。

240966 次浏览

Try this:

.menu a.main-nav-item:hover { }

In order to understand how this works it is important to read this the way the browser does. The a defines the element, the .main-nav-item qualifies the element to only those which have that class, and finally the psuedo-class :hover is applied to the qualified expression that comes before.

Basically it boils down to this:

Apply this hover rule to all anchor elements with the class main-nav-item that are a descendant child of any element with the class menu.

Cascading is biting you. Try this:

.menu > .main-nav-item:hover
{
color:#DDD;
}

This code says to grab all the links that have a class of main-nav-item AND are children of the class menu, and apply the color #DDD when they are hovered.

One common error is leaving a space before the class names. Even if this was the correct syntax:

.menu a:hover .main-nav-item

it never would have worked.

Therefore, you would not write

.menu a .main-nav-item:hover

it would be

.menu a.main-nav-item:hover

how about .main-nav-item:hover

this keeps the specificity low

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

try this

.div
{
text-decoration:none;
font-size:16;
display:block;
padding:14px;
}


.div a:hover
{
background-color:#080808;
color:white;
}

lets say we have a anchor tag used in our code and class"div" is called in the main program. the a:hover will do the thing, it will give a vampire black color to the background and white color to the text when the mouse is moved over it that's what hover means.

I found if you add a !important, it works when previously it didn't.

    a.main-nav-item:link {
color: blue !important;
}
a.main-nav-item:visited {
color: red !important;
}
a.main-nav-item:hover {
color: purple !important;
}
a.main-nav-item:focus {
color: green !important;
}
a.main-nav-item:active {
color: green !important;
}

Also, I've read somewhere that the order is important. The mnemonic "LoVe HaTe" helps you remember it: link -> visited -> hover -> active