Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute positioning working without relative positioning in the parent

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>
like image 355
Abhishek Avatar asked Jul 01 '16 12:07

Abhishek


1 Answers

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.

like image 173
Shaggy Avatar answered Nov 03 '22 01:11

Shaggy