Search code examples
htmlcssdrop-down-menucss-position

CSS position absolute and width of parent container in percent


I'm trying to build a HTML/CSS dropdown menu which is flexible in width. Due to the position:absolute for the second level of the navigation, I don't get the width of the first level. Removing the position:absolute will move all following elements on hover...

How can I solve this?

Here is the code:

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.level_1 > li {
  float: left;
  width: 45%;
  background-color: #2FA4CF;
  margin-right: 6px;
}

.level_1 > li:hover ul {
  display: block;
}

.level_2 {
  display: none;
  position: absolute;
  width: 45%;
}

.level_2 li {
  background-color: #535B68;
}
<ul class="level_1">
  <li>
    <a href="#">Level one (1)</a>
    <ul class="level_2">
      <li><a href="#">Level two (1)</a></li>
    </ul>
  </li>
  <li><a href="#">Level one (2)</a></li>
</ul>

<p>Paragraph</p>

See the result here: http://jsfiddle.net/5uf2Y/ Hover "Level one (1)" and you will see, that the second level is not the same size like the first level...


Solution

  • You have forgotten two elements for display 100%.

    Correction here

    1st elements forgets it's : Position relative on level_1 > li

    .level_1 > li {
        float: left;
        width: 45%;
        background-color: #2FA4CF;
        margin-right: 6px;
        **position:relative;**
    }
    

    2nd elements corrections it's : change size of 2nd li

    .level_2 {
        display: none;
        position: absolute;
        width: 100%;
    }
    

    With "width:100%" on .level_2 it automatically turns out with the width of its parent.