Stay Style of Hover When Opening a Dropdown Submenu

Asked

Viewed 756 times

2

I need the color of hover remain when opening the submenu.
My submenu works, I just want to be marked the menu to which it is linked.
Follow the example 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 running here: http://jsfiddle.net/ze8xtpxt/

1 answer

2


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

First we’ll apply a class to the main list so that it is easier to work with it and to point out more precisely what we want to modify or apply styles, to avoid possible conflicts in the future with other lists.

This class will be called .menu for example, which 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 make such a simple modification in the CSS code.
If you look at your CSS code, you have something like:

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

We will replace this bit of code with the code below, which will do the same job that it was already doing, only it will now also apply the desired style, which is to stay active (i.e., with that color of background darker grey) when we are doing hover over the sub-menu.

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

Here are the results and online example in jsFiddle.

  • 1

    That’s right! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.