During my attempts to display a dropdown menu when the user hovers over a button, I encountered an issue where the dropdown only appeared when I added the hover action to the parent container div. When attempting to change the .dropdown:hover selector to .dropdownbtn:hover (the fourth selector that changes the display to block), it did not work, potentially causing problems in practical scenarios. I am wondering why this is happening – could it be related to the positioning of elements?
If you'd like to see the code in action, check out the fiddle here.
* {
font-family: sans-serif;
font-weight: bold;
margin: unset;
text-decoration: none;
}
.dropdownbtn {
border: 0ch;
min-width: 50px;
min-height: 50px;
background-color: rgb(58, 199, 58);
}
.dropdown:hover .dropdownbtn {
background-color: rgb(44, 151, 44);
}
.dropdown:hover ul.menu {
display: block;
}
.dropdown {
position: relative;
display: inline-block;
margin: 10px;
text-align: center;
}
.dropdown-content {
position: absolute
}
ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}
ul>li {
display: flex;
align-items: center;
justify-content: center;
}
.menu {
display: none;
box-shadow: 10px 0px 95px 0.1px rgba(0, 0, 0, 0.472);
}
.menu>li {
text-decoration: none;
min-width: 105px;
min-height: 50px;
padding: 10px;
background-color: rgb(58, 199, 180);
border-bottom: black 1px;
}
.menu>li:hover,
.sub-menu>li:hover {
background-color: rgb(47, 148, 134);
}
.sub-menu-toggle {
position: relative;
}
.sub-menu {
position: absolute;
display: none;
left: 125px;
top: 0px;
background-color: rgb(58, 199, 180);
box-shadow: 10px 0px 95px 0.1px rgba(0, 0, 0, 0.472);
}
.sub-menu>li {
padding: 10px;
min-height: 50px;
min-width: 105px;
}
.sub-menu-toggle:hover .sub-menu {
display: block;
}
.dropdown-content li::before {
content: ;
}
<div class="dropdown">
<button class="dropdownbtn">Dropdown button</button>
<div class="dropdown-content">
<ul class="menu">
<li><a href='#'>Home</a></li>
<li class="sub-menu-toggle">
<a href='#'>Products</a>
<ul class="sub-menu">
<li><a href='#'>Product 1</a></li>
<li><a href='#'>Product 2</a></li>
<li><a href='#'>Product 3</a></li>
<li><a href='#'>Product 4</a></li>
</ul>
</li>
<li><a href='#'>Contact</a></li>
</ul>
</div>
</div>