Is it Possible to Open a Dropdown Menu by Hovering Over a Sibling Element?

Viewed 103

I have to make a few changes to the menu of my company's website, including a dropdown menu. The thing is, our website is made with Prestashop, which kind of messed up the hierarchy of the HTML. It pretty much looks like this:

<ul class ="menu">
    <li>
        <a href="" class="sf-with-menu">
        <ul class ="submenu">
            <li>
                <a href="">
            </li>
            <li>
                <a href="">
            </li>
        </ul>
    </li>
</ul>

I want to have the ul with the class .submenu open when I hover on .sf-with-menu, which are both at the same level in the page's hierarchy. Is that possible only with CSS? I'm very limited with Prestashop regarding the HTML, since I've read changing the HTML would basically break everything when we update our modules, so I'd like to stick to CSS only if possible.

1 Answers

I suppose you could use the + selector, which selects "elements that [are] placed immediately after (not inside) the first specified element," like this:

<ul class ="menu">
    <li>
        <a href="" class="sf-with-menu">Anchor</a>
        <ul class ="submenu">
            <li>
                <a href="">One
            </li>
            <li>
                <a href="">Two
            </li>
        </ul>
    </li>
</ul>


<style>
  .submenu {
    display: none;
  }
  .sf-with-menu:hover + .submenu {
    display: initial;
  }
</style>

This applies the styles to every instance of .submenu placed immediately after .sf-with-menu, when hovering over .sf-with-menu.

It will only highlight the first instance though, as you can see in this demo, so if you have the structure:

.menu
    li
     .sf-with-menu
     .submenu
         // stuff in menu
     .submenu
         // stuff in menu

...then only the first submenu will be opened on hover.

demo

See here for more CSS info.

Related