I am trying to wrap my head around a tutorial, where the .dropdown-content
is placed absolute
, but there is no parent containing the relative
or absolute
is there.
I have followed many tutorials, where it is mentioned that if there is no such parent, it will be attached to the <body>
tag. Why is this absolute positioning is required here.
I also came across this, which talks about non necessity of such positioned parent.
Here's the code from the tutorial:
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a,
.dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover,
.dropdown:hover .dropbtn {
background-color: red;
}
li.dropdown {
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
# What is the significance of this,
since there is no positioned parent. background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {
background-color: #f1f1f1
}
.dropdown:hover .dropdown-content {
display: block;
}
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li class="dropdown">
<a href="#" class="dropbtn">Dropdown</a>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</li>
</ul>
<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Hover over the "Dropdown" link to see the dropdown menu.</p>
There are no positions (bottom
, left
, right
or top
) defined for that element so it will therefore sit in the position it would sit in without the absolute positioning; all the absolute positioning is doing in this case is taking it out of the normal flow of the page so that it doesn't affect the size of its parent. Try removing the position
property and see what happens.
You should also note that, if an absolutely positioned element is not a descendant of a positioned (be it absolute
, fixed
, relative
or sticky
) element then its positions are set relative to the viewport.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With