In my nav bar i have 4 <li>
items which on :hover
i would like a drop-down menu to appear under the <li>
element which has 3 different links.
The problem is when :hover
is active the drop-down displays but then the 3 other <li>
elements move underneath the nav bar when they should not move at all.
I have tried using position:absolute
on nav ul li
elements but that just squishes them all on top of each other.
nav bar
nav ul li:hover
nav ul li
{position:absolute;}
html
<nav>
<ul>
<li>
<button>Home</button>
<div >
<a href="#">Link A</a>
<a href="#">Link B</a>
<a href="#">Link C</a>
</div>
</li>
<li>
<button>Profile</button>
<div >
<a href="#">Link A</a>
<a href="#">Link B</a>
<a href="#">Link C</a>
</div>
</li>
...
..
.
</ul>
</nav>
css
nav {
border-bottom: 0.1rem rgb(228, 220, 220) solid;
position:fixed;
width: 100%;
z-index: 5;
height: 3rem;
background-color: white;
top:0;
}
nav ul {
display: flex;
flex-direction: row;
justify-content: space-around;
width: 50%;
margin-left: 25%;
position: absolute;
}
nav ul li {
/* position:absolute; */
list-style: none;
display: flex;
justify-content: center;
flex-direction: column;
}
nav ul li button {
background-color: transparent;
border: none;
font-size: medium;
}
.dropdown-content {
display: none;
justify-content: center;
flex-direction: column;
text-align: center;
border: 0.1rem rgb(228, 220, 220) solid;
border-top: none;
margin-top: 0.8rem;
width: 5rem;
}
.dropdown-content a {
background-color: white;
padding: 0.4rem 0 0.4rem;
}
.dropdown-content a:hover {
background-color: whitesmoke;
}
nav ul li:hover .dropdown-content {
display: flex;
}
CodePudding user response:
The absolute position should be added to the dropdown-content
div. You can find an example below :
nav {
border-bottom: 0.1rem rgb(228, 220, 220) solid;
position:fixed;
width: 100%;
z-index: 5;
height: 3rem;
background-color: white;
top:0;
}
nav ul {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: flex-start;
width: 50%;
margin-left: 25%;
position: absolute;
height: 100%;
margin: 0;
}
nav ul li {
list-style: none;
display: flex;
flex-direction: column;
height: 100%;
position: relative;
}
nav ul li button {
background-color: transparent;
border: none;
font-size: medium;
height: 100%;
}
.dropdown-content {
display: none;
justify-content: center;
flex-direction: column;
text-align: center;
border: 0.1rem rgb(228, 220, 220) solid;
border-top: none;
margin-top: 0;
width: 5rem;
position: absolute;
top: calc(100% - 1px);
}
.dropdown-content a {
background-color: white;
padding: 0.4rem 0 0.4rem;
}
.dropdown-content a:hover {
background-color: whitesmoke;
}
nav ul li:hover .dropdown-content {
display: flex;
}
<nav>
<ul>
<li>
<button>Home</button>
<div >
<a href="#">Link A</a>
<a href="#">Link B</a>
<a href="#">Link C</a>
</div>
</li>
<li>
<button>Profile</button>
<div >
<a href="#">Link A</a>
<a href="#">Link B</a>
<a href="#">Link C</a>
</div>
</li>
</ul>
</nav>