I have a dropdown menu similar to the one here. i need the same behaviour except that the dropdown-content
class should hide when the user clicks on any of the item. I am looking for a possible CSS solution for this so that i don't have to write any JS for the same.
I tried different ways, but didn’t get the behaviour i needed due to the specificity. any inputs will be highly appreciated.
CodePudding user response:
You should use display: none
. Or write it in JS like so:
document.getElementById("dropdown-content-id").style.display = "none";
CodePudding user response:
just to add to what acharb07 said, simply add a script tag in your HTML doc. Though it isn't generally preferred to write your JS in your HTML, but in your case, it seems about right. your code would be
<script>document.getElementById("dropdown-content-id").style.display = "none";</script>
simple as that.
CodePudding user response:
This is not the proper way, though you can achieve what you want by the use of focus-within
pseudo attribute.
just need to add the below style.
.dropdown-content:focus-within {
display:none !important;
}
check below the updated example that you gave as an example.
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content:focus-within {
display:none !important;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #ddd;}
.dropdown:hover .dropdown-content {display: block;}
.dropdown:hover .dropbtn {background-color: #3e8e41;}
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div >
<button >Dropdown</button>
<div >
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>