简体   繁体   中英

Wrong padding for background color on ul li:hover in CSS3?

I try to make a horizontal menu bar with a table in HTML using CSS to design it. But the padding doesn't work the way I think it should: when I'm trying to change the background color of the whole li when the user "hovers it" with the mouse. But the padding seems to get wrong.

Here's my code in CSS (using Sassy CSS):

/* just to be sure the default of browser doesn't change look */
* {
    margin:0;
    padding:0;
}

/* some other design code ... */

#nav-menu {
    padding:5px;
    text-align:center;

    /* change background: browser specific gradient */
    background:$menu-bgcolor;

    li {
        list-style:none;
        display:inline;
        padding:2px 10px 2px 10px;

        :hover {
            background-color:$deco-dark;
            color:$deco-verylight;
        }
    }           
}

But the result looks something like the following:

悬停状态下的菜单项 - 您可以看到填充不包括所有li区域。

As you can see the changed background color, which is $deco-dark in this case, doesn't affect the whole li area (the area with gradient), as i would expect. What can I do to change this behavior?

With SASS, the following:

li {
  :hover { } }

will apply styles to any :hover elements inside the li . What you need is

li {
  &:hover {} }

which will apply the style to the li element itself when it's hovered. Right now, the style is likely being applied only to the a inside the li .

Try changing your li's to display: inline-block; instead.

You could also place anchors in the li, then style the anchors accordingly. This is what I usually do. Also, like Brant said, are you using a list or a table? A list is probably better and is what you have implemented so just use that.

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