CSS position absolute and width of parent container in percent
HtmlCssDrop Down-MenuCss PositionHtml Problem Overview
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...
Html Solutions
Solution 1 - Html
You have forgotten two elements for display 100%.
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.
Solution 2 - Html
Add position:relative
to level_1 > li
.level_1 > li {
float: left;
width: 45%;
background-color: #2FA4CF;
margin-right: 6px;
position:relative;
}
Solution 3 - Html
Try to set the body { width:100%;}
property, it will fix this issue, like shown below (added to your original CSS):
body{ width:100%;}
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;
}
Solution 4 - Html
Hey man you have a margin of 6px
on your first row li
thats why its a little bigger. I would use a margin left rather than right. That should fix the spacing.