How to get 'hover' and 'active' st

2019-07-06 22:32发布

I have 3 menu items in a header at the top of my website (it's not live at the moment so I can't provide a link - sorry). The 3 'buttons' are not buttons in the CSS buttons sense - they're text rendered to images (Not ideal, I know but they look pretty, so...).

Anyway, each image contains differing versions: 1 for the default appearance, 1 for mouseover and another for onclick/active. The html and CSS I'm using so far looks like this:

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;}

For one reason or another, the 'hover' and 'active' states are having no effect. I note that if I define classes for each of the buttons instead of id's, it works fine - but this makes no sense to me. The buttons each have their own image and widths and so are unique (which is why I've given them id's rather than classes).

Can anyone explain where I'm going wrong? I'm new to all this so any explanations will need to be in laymen's terms.

2条回答
在下西门庆
2楼-- · 2019-07-06 23:16

The problem is that your ID selectors are more specific than your class + pseudoselector combination. But if you don't specify the position in the ID selector, you'll be fine. EG:

#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;}
查看更多
叼着烟拽天下
3楼-- · 2019-07-06 23:16

The reason it doesn't work with ids but does work with classes is that ids will override because they are more 'specific'.

When faced with conflicts, CSS order of precedence includes how specifically the style matches the element and ids are the most specific you can get.

Is there a reason you don't want to just use classes? In the semantic web, classes would generally be favored as way to handle this very situation.

查看更多
登录 后发表回答