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...
Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow.
position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static . Have your four divs nested inside the target div, give the target div position: relative , and use position: absolute on the others.
The one key thing to remember when trying to position a child div relative to it's parent is that the child should be given the CSS property position:absolute; and the parent set to either position:absolute; or position:relative;.
If you position it as absolute , then you're positioning it relative to its closest ancestor which is fixed or relative ... Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.
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.
Add position:relative
to level_1 > li
.level_1 > li { float: left; width: 45%; background-color: #2FA4CF; margin-right: 6px; position:relative; }
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