设置 a:hover 基于类

2022-01-22 00:00:00 colors hover html css anchor

我有以下 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 设置为特定颜色.所以我写:

In CSS, I want to set the a:hover for these menu items to a particular color. So I write:

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

但是,我只想为具有类 main-nav-item<a> 标记设置此 a:hover 颜色> 而不是 main-nav-item-current,因为它具有不同的颜色并且在悬停时不应该改变.menu div 中的所有 <a> 标记都应在悬停时更改颜色,但具有 current 类的标记除外.

But, I want to set this a:hover color only for those <a> tags with the class main-nav-item and not the main-nav-item-current, because it has a different color and shouldn't change on hover. All <a> tags within the menu div should change color on hover except the one with the current class.

如何使用 CSS 来实现?

How can I do it using CSS?

我尝试了类似的东西

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

认为只有具有 main-nav-item 类的才会在悬停时改变颜色,而不是当前的.但它不起作用.

thinking that only ones with main-nav-item class will change color on hover, and not the current one. But it is not working.

推荐答案

试试这个:

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

为了理解它是如何工作的,以浏览器的方式阅读它是很重要的.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.

基本上可以归结为:

将此悬停规则应用于所有具有 main-nav-item 类的锚元素,这些锚元素是具有 menu 类的任何元素的后代子元素.

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.

相关文章