如何让'hover'和'active'状态使用 CSS 和 HTML?



我网站顶部的标题中有 3 个菜单项(目前它还没有上线,所以我无法提供链接 - 抱歉)。这 3 个"按钮"不是 CSS 按钮意义上的按钮 - 它们是渲染到图像的文本(不理想,我知道,但它们看起来很漂亮,所以......

无论如何,每个图像都包含不同的版本:1 个用于默认外观,1 个用于鼠标悬停,另一个用于点击/活动。到目前为止,我使用的 html 和 CSS 如下所示:

.HTML

<li>
    <a id="About" class="button" href="About Us.cshtml">About Us</a>
</li>
<li style="margin-left: 30px;">
    <a id="Services" class="button" href="Services.cshtml">Services</a>
</li>
<li style="margin-left: 30px;">
    <a id="Contact" class="button" href="Contact Us.cshtml">Contact Us</a>
</li>

.CSS

#About {background: url(../Buttons/About.png) no-repeat 0 0; width: 87px;}
#Services {background: url(../Buttons/Services.png) no-repeat 0 0; width: 112px;}
#Contact {background: url(../Buttons/Contact.png) no-repeat 0 0; width: 117px;}
a.button {height: 20px; display: inline-block;}
a.button:hover {background-position: 0 -20px;}
a.button:active {background-position: 0 -40px;}

由于某种原因,"悬停"和"活动"状态不起作用。我注意到,如果我为每个按钮而不是 id 定义类,它工作正常 - 但这对我来说毫无意义。每个按钮都有自己的图像和宽度,因此是唯一的(这就是为什么我给它们id而不是类的原因)。

谁能解释我哪里出错了?我对这一切都是新手,所以任何解释都需要用外行的术语。

问题是你的 ID 选择器比你的类 + 伪选择器组合更具体。但是,如果您不在 ID 选择器中指定位置,则没问题。例如:

#About {background-image: url(../Buttons/About.png); width: 87px;}
#Services {background-image: url(../Buttons/Services.png); width: 112px;}
#Contact {background-image: url(../Buttons/Contact.png); width: 117px;}
a.button {height: 20px; display: inline-block; background-repeat: no-repeat}
a.button:hover {background-position: 0 -20px;}
a.button:active {background-position: 0 -40px;}

它不适用于 ids 但适用于类的原因是 id 将覆盖,因为它们更"具体"。

当遇到冲突时,CSS 的优先顺序包括样式与元素的匹配程度,并且 id 是您可以获得的最具体的

您不想只使用类有什么原因吗? 在语义网中,类通常被推荐为处理这种情况的方式。

最新更新