Home > database >  position: relative; position: absolute; in drop down list
position: relative; position: absolute; in drop down list

Time:05-09

At https://www.w3schools.com/css/css_dropdowns.asp It puts

position: relative;
position: absolute;

for

.dropdown
.dropdown-content

respectively.

I removed them as follows and seems it still works, are they important?

.dropdown {    
display: inline-block;
  }
  
  .dropdown-content {
display: none;     
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
  }
  
  .dropdown:hover .dropdown-content {
display: block;
  }
<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style></style>
  </head>
  <body>
<div >
    <span>Mouse over me</span>
    <div >
      <p>Hello World!</p>
    </div>
  </div>
  </body>
</html>

CodePudding user response:

If you don't add it, it will shift the next elements.

.position-relative{
  position:relative;
}

.position-absolute{
  position:absolute;
}

.dropdown {    
  margin-left:30px;
  display: inline-block;
}

.dropdown-content {
  display: none;     
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
<div >
  <span>Relative Position</span>
    <div >
      <p>Absolute Position</p>
    </div>
  </div>
<div>No shift</div>

<div >
  <span>Mouse over me</span>
    <div >
      <p>Hello World!</p>
    </div>
  </div>
<div>Hi</div>

CodePudding user response:

If you had something under dropdown with position: relative and position: absolute the dropdown will appear on top of it. If you remove it then the dropdown will appear in between and push the content after itself to the bottom.

<!DOCTYPE html>
<html>
<head>
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute; /*try commenting this line*/
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
</style>
</head>
<body>

<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>

<div >
  <span>Mouse over me</span>
  <div >
  <p>Hello World!</p>
  </div>
</div>
<p>Under dropdown<p>

</body>
</html>

  • Related