I am trying to create a dropdown in CSS. I have finished writing the CSS code, but the dropdown pushes all my other objects on the screen down and that is not what I want. Instead, I want to show the dropdown in front of the objects instead at the top "which would end up pushing then down".
<div >
<h1>Recommended</h1>
<div >
<div >
<div >
<i >videocam</i>
<span>Create</span>
</div>
<div >
<i >settings</i>
<span>Settings</span>
</div>
<div >
<i >person</i>
<span>Switch Account</span>
</div>
</div>
</div>
</div>
.drop-down-container{
display: flex;
align-items: center;
justify-content: space-between;
}
.dropdown-content{
display: flex;
align-items: center;
padding: 5px;
}
.dropdown-content-background{
background-color: rgb(85, 85, 85);
padding: 15px;
z-index: 2;
border-radius: 4px;
}
.dropdown-content i {
color: white;
margin-right: 5px;
}
.dropdown-content span {
color: white;
margin-left: 5px;
}
What is the best way to fix this?
CodePudding user response:
Have a look here HTML Drop Down Menu and here https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_dropdown_navbar .
Use position: relative in your menu title then position:absolute in the dropdown container. This takes the element out of the flow of the html and stops it from pushing down the rest of the content. See below
nav {
display: flex;
background-color: darkmagenta;
padding: 0.25rem 0.5rem;
}
.menu {
border: 1px solid magenta;
padding: 0.125rem;
cursor: pointer;
color: white;
position: relative;
}
.menu:hover .drop-down-container {
display: flex;
}
.drop-down-container {
display: none;
position: absolute;
top: 1.25rem;
left: 0;
align-items: center;
justify-content: space-between;
}
.dropdown-content {
display: flex;
align-items: center;
padding: 5px;
}
.dropdown-content-background {
background-color: rgb(85, 85, 85);
padding: 15px;
z-index: 2;
border-radius: 4px;
}
.dropdown-content i {
color: white;
margin-right: 5px;
}
.dropdown-content span {
color: white;
margin-left: 5px;
}
<nav>
<div >
Hover for drop down
<div >
<div >
<div >
<div >
<i >videocam</i>
<span>Create</span>
</div>
<div >
<i >settings</i>
<span>Settings</span>
</div>
<div >
<i >person</i>
<span>Switch Account</span>
</div>
</div>
</div>
</div>
</div>
</nav>Some text here that's not being moved down by the menu