Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this sub menu positioning possible with CSS alone?

Apologies for the vague question, I can't think of a succinct, descriptive one.

I'm making a drop down menu out of unordered lists, which look a bit like this....

<ul id="menu">
    <li>Menu Item</li>
    <li>Menu Item
        <ul class="sub-menu">
            <li>Sub Menu Item</li>        
            <li>Sub Menu Item</li>
        </ul>
    </li>
    <li>Menu Item</li>
</ul>

However, I'm wondering wether this sort of positioning behaviour would be possible (Images explain this better I think)

Case 1

Sub menu is centred to it's containing list item, but is wider than it's containing list-item. Sub menu is centred to it's containing list item

Case 2

Sub menu should be centered, but there's not enough left-space in the root list, so it keeps flush against the root lists left edge. submenu wont extend past the left edge root-list

Case 3

Like Case 2, but this time it's the right edge. submenu wont extend past the right edge of the root-list

I think it can be broken down into two tricky CSS problems.

  1. How to center a sub menu to it's container, despite being wider than it's container.
  2. How to prevent the submenu going beyond the bounds of the root-list element.

I'll be implementing this behaviour in Javascript since I'm on a deadline. But for future reference, it would be nice to know if this could be accomplished with CSS alone.

There's a JSFiddle here to play with if you have any theories.

like image 728
gargantuan Avatar asked Jul 12 '11 16:07

gargantuan


1 Answers

http://jsfiddle.net/AxnVU/28/

You now have a div wrapping your submenus, so you can use some tricks to position the submenus using the text-align property.

If you don't want the gray background of the submenu, you can remove that and add a background color only to the ul inside the div.submenu, to have the same effect of your pics.

The idea is: you have a div occupying all the avaiable space (the width of your big menu), which contains the submenu. The submenu, displayed inline, can be manipulated with the text-align property to stay at the left, center or right of the avaiable space.

Edit

http://jsfiddle.net/AxnVU/69/

Here is another option with more menu voices, since the previous only worked for three voices. This time we need to specify a submenu wide three times a menu voice (but could be more also), so 300% wide, and center it by giving negative left margin (-100% in this case, whih is one menu voice). Inside the submenu there is the list item horizontal center with the same trick as before.

like image 193
Jose Faeti Avatar answered Sep 28 '22 07:09

Jose Faeti