I have a dropdown menu that works as expected when using a <button>
element. The menu appears right below the button as it should be. However, when I change the element to an <a>
tag, the dropdown menu appears on top of the <a>
, not below it.
Why is the behavior different between the <button>
and <a>
elements? How can I make the dropdown menu appear below the tag just like it does with the <button>
?
Any help would be appreciated!
HTML (with a href it’s not working)
<div class="dropdown">
<a href="#" class="dropbtn">Dropdown 1</a>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
HTML (with button it’s working)
<div class="dropdown">
<button class="dropbtn">Dropdown 2</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
CSS
.dropdown {
float: left;
overflow: hidden;
}
.dropdown .dropbtn {
display: block;
background-color: #1f7ac4;
color: #f2f2f2;
border: 1px solid #1f7ac4;
text-align: center;
padding: 14px 16px;
margin: 0px 0px 0px 0px;
text-decoration: none;
font-size: 19px;
line-height: 36px; /* Must be the same as font-size .topnav a.logo */
}
.dropdown .dropbtn:hover{
background-color: #2f8fde;
border-top-left-radius: 12px;
border-top-right-radius: 12px;
border-bottom-left-radius: 12px;
border-bottom-right-radius: 12px;
border: 1px solid #2f8fde;
color: #f2f2f2;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #ffffff;
border-top-left-radius: 12px;
border-top-right-radius: 12px;
border-bottom-left-radius: 12px;
border-bottom-right-radius: 12px;
border: 1px solid #d6d2d2;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
min-width: 160px;
margin: 0px 0px 0px 0px;
padding: 10px 10px 5px 10px;
z-index: 1;
}
.dropdown-content a {
float: none;
background-color: #ffffff;
border-top-left-radius: 12px;
border-top-right-radius: 12px;
border-bottom-left-radius: 12px;
border-bottom-right-radius: 12px;
border: 0px;
color: #3c4043;
text-decoration: none;
display: block;
font-size: 16px;
line-height: 32px;
text-align: left;
margin: 0px 0px 5px 0px;
}
.dropdown-content a:hover {
background-color: #f5f5f5;
color: #3c4043;
border: 0px;
}
.dropdown:hover .dropdown-content {
display: block;
}
I found the following solution
I changed margin: 66px 0px 0px 0px;
at .dropdown-content
.
Is this a good solution? With the <button>
I didn’t need a fixed margin.
2
Answers
Make sure to adjust the CSS to make sure the dropdown starts below the anchor tag just like it does for the button.
Here is an example:
A problem is that you are setting all a element descendants of .topnav with
.topnav a
which I think should be.topnav > a
i.e. target only the direct children.