Currently, I am in the process of developing navigation buttons that trigger a dropdown sub-menu when clicked by utilizing checkbox inputs. Upon clicking the label, the input is checked, causing the menu to drop down, and when the label is clicked again, the menu collapses back up.
However, I am now faced with a specific requirement. I am attempting to design the dropdown menu in such a way that it collapses when any HTML element is clicked, eliminating the need for the user to click on a specific element to close the menu.
Below is the HTML & CSS code tailored for the dropdown menu:
<ul class="down-bar" style="list-style:hidden">
<div class="dropdown">
<input type="checkbox" value="drop" id="drop-1" class="dropper">
<li><label class="down-nav" id="down-nav-1" for="drop-1" style="text-decoration:none">Click <b class="caret"> ▼</b></label></li>
<div class="dropdown-menu">
<a href="#">Link</a>
</div>
</div>
CSS:
.dropdown {
display: inline-block;
float: left;
padding-top: 0em;
transition: 0.1s ease-in;
margin-top: 1.5%;
white-space: nowrap;
}
.dropdown-menu {
float: left;
display: none;
top: 0%;
margin-top: 2.2%;
width: 8%;
min-width: 50px;
padding-left: 18px;
background-color: rgba(26, 26, 26, 2);
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 99;
list-style-type: none;
transition: 0.1s ease-in;
border-color: black;
border-radius: 3px;
}
.dropdown-menu a {
color: white;
font-size: 0.9em;
padding: 0px 2px 0px 0px;
text-decoration: none;
display: block;
list-style-type: none;
white-space: nowrap;
left: 0%;
margin-left: 0%;
}
.dropdown-menu a:hover {
color: #C90205;
}
.dropper {
display: none;
visibility: hidden;
}
.dropper:checked ~ .dropdown-menu {
display: block;
z-index: 99;
}
.dropper:checked ~ li #down-nav-1 {
border: solid 3px gray;
background-color: gray;
margin-top: 1.5%;
margin-left: 3%;
border-radius: 10px;
}
In my attempts, I experimented with different approaches, including using a full-width anchor tag. However, this caused the main menu to disappear. I considered utilizing the :active
tag to revert the menu's display back to None
. You can view the full code (remove comment tags for full-width example).
Ultimately, I am seeking a solution that doesn't result in other elements disappearing. Do any errors exist in my code? Is the initial example a viable solution, and if so, in what way? How can I ensure the menu collapses when the user clicks any HTML element? Is it feasible to achieve this without resorting to Javascript?