ray ray - 7 months ago 10
HTML Question

Trying to get drop down to appear when hovering single menu item, not entire menu

I currently have a

section
that is a flex box. I am trying to get a drop down menu to appear when I mouse over the
Vs
div. Unfortunately, this div is inside a
section
tag and the drop down menu won't appear.

The way the code is currently set up causes the drop down menu to appear when I mouse over any part of the section. I want the drop down menu to only appear when I mouse over the
Vs.
div.

Here is an image of the section.

enter image description here



.line {
height: 4px;
flex: 1;
background: red;
margin: 0 10px;
}
section {
display: flex;
align-items: center;
}
.home {
margin-left: 50px;
}
.m {
margin-right: 30px;
}
.logout {
margin-right: 50px;
}
ul {
list-style-type: none;
margin-top: 20px;
}
.dropDown:hover ~ .dropDownContent {
display: block;
}
.dropDownContent {
display: none;
}

<section class="dropDown">
<div class="home">Home</div>
<div class="line"></div>
<div class="m">Reports</div>
<div class="m dropDownVs">Vs.</div>
<div class="logout"> <a href="url"> Log Out </a>
</div>
</section>

<div class="dropDownContent">
<ul>
<li>name 1</li>
<li>name 2</li>
<li>name 3</li>
</ul>
</div>





Bonus: Any suggestions on aligning the drop down directly below the Vs. div and suggestions for selecting the drop down items when the mouse is off the Vs. div would be appreciated. Currently when I mouse off the section the dropdown disappears and a user is unable to select anything.

Answer

In your code you have the drop-down menu positioned as a sibling to the main menu. It's better to nest the drop-down within the related main menu item. Try this:

ul {
  display: flex;
  list-style-type: none;
  margin-top: 20px;
}
ul > li:hover {
  background-color: aqua;
  cursor: pointer;
}
.dropDownVs > ul {
  display: none;
}
.dropDownVs:hover > ul {
  display: flex;
  flex-direction: column;
  padding-left: 0;
}
.home {
  margin-left: 50px;
}
.line {
  flex: 1;
}
.m {
  margin-right: 30px;
}
.logout {
  margin-right: 50px;
}
<ul class="dropDown">
  <li class="home">Home</li>
  <li class="line"><hr></li>
  <li class="m">Reports</li>
  <li class="m dropDownVs">Vs
    <ul>
      <li>name 1</li>
      <li>name 2</li>
      <li>name 3</li>
    </ul>
  </li>
  <li class="logout"><a href="url">Log Out </a>
    <li>
</ul>