Staying hover style when opening a Dropdown submenu

2

I need the color of hover to remain when opening the submenu. My submenu works, I just want it to be marked the menu it's linked to. Here is the sample code:

HTML:

<ul>
  <li><a href="#">Link 1  &raquo;</a>
      <ul>
          <li><a href="#">Link 2</a></li>
          <li><a href="#">Link 3</a></li>
          <li><a href="#">Link 4</a></li>
      </ul>
  </li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
</ul>

CSS:

ul {
    width: 200px;
    background: #ccc;
    list-style: none;
    padding: 0;
    border: 1px solid #999;
}

ul li {
    border-bottom: 1px solid #999;
    position: relative;
}

ul li:last-child {
    border-bottom: none;
}

ul li a {
    color: #000;
    display: block;
    padding: 5px;
}

ul li a:hover {
    background:#999;
}

ul li ul {
    display:none;
    position: absolute;
    top:0;
    left: 200px;
}

ul li:hover > ul {
    display: block;
}

You can see it working here: link

    
asked by anonymous 18.09.2015 / 00:34

1 answer

2

This is possible with a small change in your CSS code.

First let's apply a class to the main list to make it easier to work with and to more accurately point to what we want to modify or apply styles to avoid future conflicts with other lists.

This class will be called .menu for example, that applied in the HTML code will be:

<ul class="menu">
    <li><a href="#">Link 1  &raquo;</a>
        <ul>
            <li><a href="#">Link 2</a></li>
            <li><a href="#">Link 3</a></li>
            <li><a href="#">Link 4</a></li>
        </ul>
    </li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
    <li><a href="#">Link 4</a></li>
</ul>

Then we will then make such a simple modification in the CSS code. If you notice your CSS code, you have something like:

ul li a:hover {
    background:#999;
}

We will replace this piece of code with the code below, which will do the same work he was already doing, but he will now also apply the desired style, which is to stay as active (ie with that color of the background gray) when we are doing hover on the sub-menu.

.menu li:hover > a {
    background:#999;
}
  

Here you have the result and online example in jsFiddle .

    
18.09.2015 / 02:46