I recently encountered a common issue in CSS involving flyout menus with sub-menus that are shown on hover. When attempting to position the sub-menu directly below the parent list item, I used position:relative;
on the parent item and position:absolute;top:0;
on the submenu. This approach worked well for vertical alignment.
However, by using position:relative;
, I lost the ability to make the submenu 100% width of the page and align it to the very left edge of the page rather than the parent element.
My goal is to maintain vertical alignment with position:relative;
on the parent, while inheriting horizontal alignment with position:inherit;
.
In the example below, you can see that the submenus are aligned correctly vertically but should start at the very left horizontally:
.clearfix::after {
content: "";
clear: both;
display: table;
}
#my-menu-inner > ul {
width: 100%;
background-color: yellow;
list-style-type: none;
}
#my-menu-inner > ul > li {
float: left;
position: relative;
padding: 20px;
border: 1px solid black;
margin: 20px;
}
#my-menu-inner > ul > li > div.sub{
position: absolute;
top: 60px;
background-color: red;
padding: 40px;
display: none;
left: 0;
width: 100vw;
}
#my-menu-inner > ul > li:hover > div.sub, #my-menu-inner > ul > li:focus > div.sub {
display: block;
}
<div id="whatever">Just something before ...</div>
<div id="my-menu">
<div id="my-menu-inner">
<ul class="clearfix">
<li>
<span>foo</span>
<div class="sub">
<ul>
<li>hello</li>
<li>world</li>
</ul>
</div>
</li>
<li>
<span>foo</span>
<div class="sub">
<ul>
<li>please</li>
<li>alignme</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
How can I achieve my desired layout using only pure CSS (answers involving JS will not be accepted)?