Building a vertical, nested CSS menu that works in IE7
Using just CSS (and JS to apply :hover styles), what's the best way to build horizontal dropdown nested menus?
I'm trying to adopt the menus here, but I can't achieve the positioning I want. Every time I attempt this, I wind up with so much CSS cludge that it's no longer manageable.
DOM:
<nav>
<ul>
<li>
<a href="#">Heading 1</a>
<ul>
<li><a href="#">1</a>
<ul><li>a</li><li>b</li></ul>
</li>
<li>2</li><li>3</li>
</ul>
</li>
<li>
<a href="#">Heading 2</a>
<ul><li>1</li><li>2<开发者_如何学C;/li><li>3</li></ul>
</li>
</nav>
Desired output:
That is, the top header is entirely horizontal, the first menu beneath each header lines up horizontally on the left of the header, and all further submenus line up horizontally on the right and vertically on the top. How would I go about building this basic idea?
I was able to create one myself but I am not sure if it good enough or not. I'd rather suggest that you look at jQuery UI Development & Planning Wiki > Menu page. The page lists a couple of menus.
Also, this is a very simple script for creating dropdown menus which might serve as a starting point.
Edit
To create dynamic CSS popup menus, you'll need jQuery support, mainly because (i) you have to position the sub-menus dynamically (ii) leverage the "hover" events which is not possible with a CSS only solution.
- Your main-menu
<ul>
should beposition: static
- All of your
<li>
that contain a sub-menu should beposition: relative
- All of your sub-menu
<ul>
should beposition: absolute
anddisplay: none
.
You can then implement hover
event on all <li>
elements that contain a sub-menu. On hover, you first position the <ul>
that is nested directly within that <li>
, then you show it. The hover event also provides an event that fires when that element is "un-hovered". In this event you simply hide the corresponding <ul>
. Easy?
To position the <ul>
which is a sub-menu, just grab the width of the containing <li>
and set the left: XXXpx; top: 0
on the <ul>
you're about to display. If the sub-menu is to appear below the <li>
then instead you grab the height of the <li>
and set the left: 0; top: YYYpx
on the <ul>
. The absolute-relative combination makes such kind of positioning possible.
At this point you can also consider implementing "edge detection"... that is to check if the menu expands past the right or bottom edge of the view port. Pretty tricky.
Note that in IE7 will have problems rendering the menus (and trigger the hover event) properly although according to the HTML specs your menu is OK. To counter this you may want to set z-indexes on your sub menus.
精彩评论