简体   繁体   中英

css hover for entire li element with padding

I am trying to give the menu elements a hover, but they are also having a padding: 10px; and as the result of that the :hover: background-color: will start from the 10px padding.

Any idea how to solve the problem? Here's a jsfiddle demo for that: http://jsfiddle.net/eufqg7d9/

This is caused by the default padding of the UL. You can either explicitly set this to padding: 0 or use a reset like http://meyerweb.com/eric/tools/css/reset/ .

Here is your fiddle with a this reset applied: http://jsfiddle.net/h3erxugg/

You can also skip adding extra classes (like "list-item") and simply target the 'li' element itself within the #menu "namespace". Here's an example of what I mean:

<div id="menu">
  <ul>
    <li>Menü #1</li>
    <li>Menü #2</li>
    <li>Menü #3</li>
  </ul>
</div>

And then the corresponding CSS would look something like this:

#menu ul {
  list-style: none;
}

#menu li {
  padding: 10px;
}

#menu li:hover {
  opacity: 0.7;
  background-color: red;
}

Updated fiddle: http://jsfiddle.net/eufqg7d9/3/

li.menu-item:hover {
    margin-left: 10px;
    padding-left: 0px;
    opacity: 0.7;
    background-color: red;
}

Since it was unclear what you were asking I have made you another fiddle: http://jsfiddle.net/eufqg7d9/6/ . This basically creates the effect of your picture.

ul {
  margin: 0;
  padding: 0;    
}

li {
    margin: 0;
}

div#main {

    width: 900px;
    height: auto;
    border: 1px solid #ccc;
    margin: 0 auto;
}

div#menu {

    width: 300px;
    height: auto;
    float: left;
    background-color: yellow;
}

ul.menu-list {

    list-style: none;
}

li span {
    margin-left: 40px;
}

li.menu-item {
    width: auto;
    padding: 10px;
}

li.menu-item:hover {

    opacity: 0.7;
    background-color: red;
}

Try to update this portion of css.

ul.menu-list {
   list-style: none;
   padding-left: 0;
}

I have added padding-left: 0; to remove the padding on the left side.

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