CSS dropdown submenu with dynamic width: how to align left?
Tags: html,css
Problem :
It's easy to have a LI > UL submenu show up with CSS:
.menu ul { padding-left: 0px; }
.menu li { list-style-type: none; display: inline-block; padding-left: 0px; margin: 1px; background: #ddd; width: 100px; }
.menu li ul { display: none; }
.menu li:hover > ul { display: block; position: absolute; background: #000; }
.menu li:hover > ul li { display: block; background: #bbb; width: auto; }
In this case, the size of the submenu automatically adjusts to the width of the content. The submenu aligns left where the left of the parent LI element is.
Let's say I want to align the submenu to the right, so the right should lign up with the parent LI's right side. I can do that by having a fixed width of the submenu, and use this (assuming the parent LI is 100px wide):
#menu-left li:hover > ul { width: 150px; margin-left: -50px; }
But then you can't use flexible width submenu's anymore. Also, you need to know the width of the parent LI.
JS Fiddle explains my question best: https://jsfiddle.net/ybc0uxq8/1/
Anyone knows a way to have the right side of the sub UL lign up with the right side of the parent LI without needing a fixed submenu width, and allowing for a submenu width larger than the parent LI?
Solution :
According to the comments/request, here is the edited version of the original CSS
code to reflect the desired result:
/* apply to both */
.menu ul { padding-left: 0px; }
.menu li { list-style-type: none; display: inline-block; position: relative; padding-left: 0px; margin: 1px; background: #ddd; }
.menu li ul { display: none; }
.menu li:hover > ul { display: block; position: absolute; background: #000; right: 0; }
.menu li:hover > ul li { background: #bbb; white-space: nowrap; }