Dropdown not showing due to overflow auto on parent
by incutonez
HTML
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="parent">
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<p>
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
some other content that causes the parent to have scrollbars
</p>
</div>
CSS
.parent {
height: 100px;
overflow: auto;
}
/* Copied from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown */
/* Except, I removed the position relative on the dropdown class per https://stackoverflow.com/a/67045978/1253609 */
/* Potentially https://codepen.io/lzhoucs/pen/KGPNaE */
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
display: inline-block;
position: relative;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 100;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
JavaScript
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}