Home > other >  Make position: absolute div the same width as the parent div
Make position: absolute div the same width as the parent div

Time:02-19

I have the following set up:

.nav-menu-container {
  display: flex;
  flex-direction: row;
  width: 100%;
  background-color: #e0e0e0;
  padding: 5px;
  box-sizing: border-box;
}

.nav-option-container {
  width: 25%;
}

.dd-parent {
  background-color: red;
}

.nav-option-dd-container {
  display: none;
  border: 1px solid black;
  background-color: #e0e0e0;
  position: absolute;
}

.dd-parent:hover .nav-option-dd-container {
  display: block;
}
<div >
  <div >
    a
  </div>
  <div >
    b
    <div >
      1
    </div>
  </div>
</div>

How can I get the nav-option-dd-container element to be the same width as the nav-option-container dd-parent parent div?

I can't use position: relative; as that will cause my outer-most nav-menu-container div to expand when the hover effect shows the dropdown div, as shown below:

.nav-menu-container {
  display: flex;
  flex-direction: row;
  width: 100%;
  background-color: #e0e0e0;
  padding: 5px;
  box-sizing: border-box;
}

.nav-option-container {
  width: 25%;
}

.dd-parent {
  background-color: red;
}

.nav-option-dd-container {
  display: none;
  border: 1px solid black;
  background-color: #e0e0e0;
  position: relative;
}

.dd-parent:hover .nav-option-dd-container {
  display: block;
}
<div >
  <div >
    a
  </div>
  <div >
    b
    <div >
      1
    </div>
  </div>
</div>

I've also seen recommendations of setting top, left, right, and bottom to 0, but with position: absolute;, that results in using the root element and ends up covering the entire page.

CodePudding user response:

You need to use position: relative on .nav-option-container, so that when setting left: 0; right: 0; in the inner child, it will refer to the bounds of its parent:

.nav-option-container {
  /* Add this */
  position: relative;
}

.nav-option-dd-container {
  /* And add these two lines */
  left: 0;
  right: 0;
}

See proof-of-concept example:

.nav-menu-container {
  display: flex;
  flex-direction: row;
  width: 100%;
  background-color: #e0e0e0;
  padding: 5px;
  box-sizing: border-box;
}

.nav-option-container {
  width: 25%;
  
  /* Add this */
  position: relative;
}

.dd-parent {
  background-color: red;
}

.nav-option-dd-container {
  display: none;
  border: 1px solid black;
  background-color: #e0e0e0;
  position: absolute;
  
  /* And add these two lines */
  left: 0;
  right: 0;
}

.dd-parent:hover .nav-option-dd-container {
  display: block;
}
<div >
  <div >
    a
  </div>
  <div >
    b
    <div >
      1
    </div>
  </div>
</div>

  • Related