简体   繁体   English

CSS 下拉菜单与 Hover 效果

[英]CSS Drop Down Menu with Hover Effect

I've got a css-based horizontal drop down menu that works perfectly well, but I'm having trouble adding an effect that adds a top border on the item that represents the page the user is currently on.我有一个基于 css 的水平下拉菜单,效果非常好,但是我无法添加一个效果,该效果在代表用户当前所在页面的项目上添加顶部边框。 Here's the HTML code for the dropdown:这是下拉列表的 HTML 代码:

<ul id="browse">
    <li>
        <a href="/comedy/">Comedy</a>
        <ul>
            <li><a href="/caddyshack/">Caddyshack</a></li>
            <li><a href="/backtoschool/">Back to School</a></li>
        <ul>
    </li>
    <li>
        <a href="/80s/">80s</a>
        <ul>
            <li><a href="/diehard/">Die Hard</a></li>
            <li><a href="/overboard/">Overboard</a></li>
        <ul>
    </li>
</ul>

Here's what I want:这就是我想要的:

  • Hovering over an item changes its background color, as well as the background of the dropdown (the nested ul element)将鼠标悬停在项目上会更改其背景颜色,以及下拉菜单的背景(嵌套的 ul 元素)

  • On the active page for an item, that item should have a 2 pixel tall colored border at the top.在项目的活动页面上,该项目的顶部应该有一个 2 像素高的彩色边框。

Just to be clear, the dropdown already works fine, and I can already identify the "active" menu item.为了清楚起见,下拉菜单已经可以正常工作,我已经可以识别“活动”菜单项。 I just can't seem to figure out how to combine changing the background color on hover and adding a border-top on the active menu item without messing up the style of the menu somehow (either leaving a 2px tall blank space on hover, or having the hover background property override the border-top property on the active item)我似乎无法弄清楚如何结合更改 hover 上的背景颜色和在活动菜单项上添加边框顶部而不以某种方式弄乱菜单的样式(在 hover 上留下 2px 高的空白空间,或者让 hover 背景属性覆盖活动项目上的border-top属性)

I should also add, CSS-only solutions please.我还应该补充一下,仅限 CSS 的解决方案。

Any help here would be much appreciated.在这里的任何帮助将不胜感激。

For the background color, it's fairly simple, just use code similar to this:对于背景颜色,它相当简单,只需使用类似这样的代码:

#browse a:hover {
     background-color: fuchsia; /*Whatever your background color is*/
}

As for the border effect, that's a little harder to do semantically, but I feel that this article on CSS specificity would do the trick.至于边界效应,这在语义上有点难,但我觉得这篇关于 CSS 特异性的文章可以解决问题。 Basically, it involves adding an id to your body, and then referencing that id in the CSS so that only the specific pages will be affected.基本上,它涉及向您的正文添加一个id ,然后在 CSS 中引用该id ,以便只有特定页面会受到影响。

EDIT: If you're having issues with your top border affecting layout (I don't know what orientation the navigation has), try reducing the margin or padding you have on each item by the size of your border (2px, in this case) to maintain overall box height.编辑:如果您的顶部边框影响布局时遇到问题(我不知道导航的方向),请尝试将每个项目的边距或填充减少边框的大小(2px,在这种情况下) 以保持整体盒子高度。 If you don't have any margins/paddings, try negative margins.如果您没有任何边距/填充,请尝试负边距。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM