Search code examples
htmlcssdrop-down-menuhoversubmenu

How to prevent a div from disappearing when you hover a link in pure css


first of all sorry for my english I'm going to try to be as precise as possible, here is my problem:

In my css I created a div displayed with none, and when I hover on a link in the nav I changed the display with display block it is a simple sub-nav pattern. But here is my problem, once i'm hovering my link when I leave it my sub menu disappears automatically, so how do I keep my sub menu in display block even if i'm not hovering the trigger anymore and all of that in pure css (it is an exercice for me):

here is my repo on github : https://github.com/MehdiAlouafi/Int-gration-Briefing-2


Solution

  • I think you made a couple of mistakes.

    /* First of all it's better to have your list-item relative. */
    nav ul > li {
      position:relative;
    }
    
    /* Then your .on-hover can have simpler top and left coordinates. */ 
    .on-hover {
      height: 150px;
      background-color: rgb(243,243,241);
      width: 165px;
      position: absolute;
      left: 0;
      top: 0;
      display: none;
      border-bottom: 1px solid rgba(96, 96, 96, 0.2);
      z-index: -1;
    }
    
    /* You want the hovering to be over the entire li.*/
    nav ul > li:hover .on-hover {
      display: block;
    }
    

    You had the hover work like this. Which means it stops hovering when you leave the #test being the anchor(<a>) element

    #test:hover + .on-hover {
    

    Working jsfiddle: https://jsfiddle.net/3su9jppc/1/