简体   繁体   中英

CSS - hovering over element affects multiple elements

I have a menu that is floating right on the screen and when hovering over one of the elements it does what it has to do, the opacity is changing of the rest and only the hovered element is emphasized. But when hovering between the elements on the empty space, a small portion of the space in the middle changes opacity to all elements. If I hover over an element near the bottom or top of it and the spaces between all elements, it does what it should. I know it has something to do with the <ul> tag but don't know how to solve it. Here is the code:

HTML

<div class="menu">
  <ul>
    <li><a>Home</a></li>
    <li><a>About</a></li>
    <li><a>Projects</a></li>
    <li><a>Services</a></li>
    <li><a>Contact</a></li>
  </ul>
</div>


CSS

.menu {
    float:right;
    margin-right: 50px;
    }
ul li {
    display: inline;
    text-decoration: none; 
    color: #003560;
    padding: 10px 50px;
    transition: all ease .3s;
    }
ul:hover li {
    color: #0089F9;
    opacity: .1;
    transition: all ease .3s;
    }
ul li:hover {
    opacity: 1;
    padding: 15px 55px;
    }
li {
    border: 2px solid #0089F9;
    border-radius: 5px;
    margin-left: 20px;
    }


https://jsfiddle.net/Vc2ug/49/

You can use float: left instead of display: inline

ul li {
    display: block;
    float: left;
    text-decoration: none; 
    color: #003560;
    padding: 10px 50px;
    transition: all ease .3s;
}

https://jsfiddle.net/7w8w86my/1/

ul:hover li {
  transition: all ease .3s;
}

Remove opacity and color properties for and make ul:hover li as above. Actually it means when moves is on ul tag, apply following properties lo li. So, when you are placing between two list items, it is on ul and so it i applying opacity to all list items.

Just add to your <ul> some padding at bottom and top. Like this:

ul {
    padding: 50px 0 50px 0;
}

Here is a demo.

只需删除<li>之间的HTML中的空格即可

Your problem that when you direct the cursor at space between li all ul becomes hovered. You need to change structure of html and to refuse use of ul or to add a small script. For example so: https://jsfiddle.net/trean/sxoxpz2e/2/ , https://jsfiddle.net/trean/sxoxpz2e/2/embedded/result/

$('.menu > ul > li').hover(function() {
        $(this).parent().find('li').addClass('unhover');
    }, function() {
        $(this).parent().find('li').removeClass('unhover');
 });

CSS:

.unhover {
    color: #0089F9;
    opacity: .1;
    transition: all ease .3s;
    }

I don't exclude that there are ways to do without jquery, but so far anything to mind doesn't come, except refusal of ul in favor of hierarchy div.

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