AleRef AleRef - 2 months ago 6
CSS Question

Css submenu not remain visible after menu unhover no javascript

I want to use only css, no javascript. When I mouse hover the top-level menu I can display the submenu, but as soon as I unhover the top-level menu the submenu disapper. How could I solve this without using javascript? Have I missed something?

I tried to use

.has-children:hover + .sub-menu {display: block;}
to display the submenu when I mouse hover the top-level menu, but I have no idea what I can code to keep visible the submenu.

The HTML code is:



.header ul {
list-style: none;
padding: 20px 30px;
}
.header li {
float: left;
position: relative;
}
.header li a {
padding: 20px 30px;
}
.menu {
clear: none;
float: right;
max-height: none;
}
.menu li ul {
position: absolute;
}
.sub-menu {
display: none;
}
.open-menu-link {
display: none;
}
.has-children:hover + .sub-menu {
display: block;
}

<header class="header">
<ul class="menu">
<li><a href="#work">Work</a></li>
<li>
<a class="has-children" href="#about">Haschildren</a>
<ul class="sub-menu">
<li><a href="#link1">Child 1</a></li>
<li><a href="#link2">Child 2</a></li>
<li><a href="#link3">Child 3</a></li>
</ul>
</li>
<li><a href="#careers">Careers</a></li>
<li>
<a class="has-children" href="#careers">About</a>
<ul class="sub-menu">
<li><a href="#link1">Child 3</a></li>
<li><a href="#link2">Child 4</a></li>
</ul>
</li>
<li><a href="#">end</a></li>
</ul>
</header>




Answer

Move you has-children class onto the li and then make your selector:

.has-children:hover > .sub-menu

Updated snippet:

.header ul {
  list-style: none;
  padding: 20px 30px;
}
.header li {
  float: left;
  position: relative;
}
.header li a {
  padding: 20px 30px;
}
.menu {
  clear: none;
  float: right;
  max-height: none;
}
.menu li ul {
  position: absolute;
}
.sub-menu {
  display: none;
}
.open-menu-link {
  display: none;
}
.has-children:hover > .sub-menu {
  display: block;
}
  <header class="header">
    <ul class="menu">
      <li><a href="#work">Work</a></li>
      <li class="has-children">
        <a href="#about">Haschildren</a>
        <ul class="sub-menu">
          <li><a href="#link1">Child 1</a></li>
          <li><a href="#link2">Child 2</a></li>
          <li><a href="#link3">Child 3</a></li>
        </ul>
      </li>
      <li><a href="#careers">Careers</a></li>
      <li class="has-children">
        <a href="#careers">About</a>
        <ul class="sub-menu">
          <li><a href="#link1">Child 3</a></li>
          <li><a href="#link2">Child 4</a></li>
        </ul>
      </li>
      <li><a href="#">end</a></li>
    </ul>
  </header>

Comments