CSS change two links when hovering over either one

2019-06-22 05:45发布

问题:

I have the following html:

<div id="main">
    <div id="home" class="section">
        <ul>
            <li class="home_li"><a href="#home" class="goto_home">Home</a></li>
            <li class="about_li"><a href="#about" class="goto_about">About us</a></li>
            <li class="contact_li"><a href="#contact" class="goto_contact">Contact</a></li>
        </ul>
    </div>  <!-- End home -->

    <div id="nav">
        <ul>
            <li class="home_li"><a href="#home" class="goto_home"></a></li>
            <li class="about_li"><a href="#about" class="goto_about"></a></li>
            <li class="contact_li"><a href="#contact" class="goto_contact">Contact</a></li>
        </ul>
    </div>  <!-- End nav -->
</div>  <!-- End main -->

What I'm trying to do is change the state of both links when one is being hovered. For example, if I hover over 'about' under <div id="home"> I want both links, that one and the one under <div id="nav">, to be displayed with opacity.

I'm trying to stay away from JS if possible. So far my attempt with CSS has been with adjacent selectors but that's new to me so I haven't been able to make it work.

    #home .about_li a:hover + #nav .about_li a {
        opacity: .5;
    }

Can this be done with only CSS?

EDIT:

Thanks for your replies. How would I need to change the HTML for the adjacent selector to work? I could give it a try and make a few tweaks if it doesn't affect seriously the rest of the site (the structure is pretty much complete by now).

ANOTHER EDIT:

Okay, I've read some more about these selectors and now I get it. I'd thought that by being all inside the main div they were siblings :P and now I see why it doesn't work. I'll see if I can come up with a workaround to use only CSS and will post back here. Otherwise I'll go with JS :(

回答1:

Unfortunately, your structure is too complex for CSS selectors alone, as the a elements aren't siblings of each other, but it's your inner divs, and so on.

It's very easy with JavaScript libraries like jQuery, otherwise you're out of luck.



回答2:

no, if you are not going to change HTML structure, or you can use jQuery



回答3:

This cannot be done with CSS; although I applaud your efforts to stay away from loading a bunch of JS, especially heavyweight libraries.