简体   繁体   中英

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. Here's the HTML code for the dropdown:

<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)

  • On the active page for an item, that item should have a 2 pixel tall colored border at the top.

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)

I should also add, CSS-only solutions please.

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. 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.

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. If you don't have any margins/paddings, try negative margins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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