I have a menu with one dropdown item. However, I can’t make it work so it open under the associated div item.
Here’s my code :
.dropdown {
position: relative;
}
.dropdown-content {
display: none;
position: relative;
background-color: #f9f9f9;
float: right;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.top-menu a{
color: black;
float: right;
right:0;
text-align: center;
padding: 24px 26px;
text-decoration: none;
}
[class*="col-"] {
float: left;
padding: 15px;
}
.col-12 {width: 100%; align-items:normal;}
.dropdown:hover .dropdown-content {
display: block;
}
<!DOCTYPE html>
<html>
<body>
<div class="col-12">
<header>
<div class="top-menu" id="myTopnav">
<div><a href="#">Item 3</a></div>
<div><a href="#" target="_blank">Item 2</a></div>
<div class="dropdown">
<a>Item 1 (dropdown)</a>
<div class="dropdown-content">
<div><a>1</a></div>
<div><a>2</a></div>
<div><a>3</a></div>
<div><a>4</a></div>
<div><a>5</a></div>
</div>
</div>
</div>
</header>
</div>
</body>
</html>
Ideally, the dropdown-content
would open directly under Item 1 (dropdown)
wherever this item is located (e.g. if Item 1
was to be located on the far right side).
Thanks in advance for your replies !
2
Answers
This issue is actually with how you laid out the navigation bar. Instead of floating the links to the right, you should display the entire nav bar using
display: flex
.THen you can do:
to position the parent element ONLY on hover. You don’t want it to always create it’s own stacking context. You only want that on hover. And, yes, nesting is now native in browsers, it doesn’t require Sass.
then you can use inset properties like
top
/left
orinset-block-start
andinset-inline-start
to position your drop-down.Pretty soon you’ll be able to use CSS anchor positioning, but that’s only in chromium for right now, but should be part of baseline 2024