HTML+CSS: List with submenu problems
im trying to build a simple HTML+CSS menu with submenu popups.
If a list item has a child list and gets hovered the child list would show up. This works already.
But I want the parent item to be on top of the child list. I tried it with the z-index and.. failed. T开发者_开发百科he child always overlaps the parent.
I try to do this to make the popup look like this:
________ ________
|Link 1| |Link 2|______
|-> Sublink 1|
|-> Sublink 2|
|____________|
So parent item and child item have no visible borders between them but borders around them.
This is the HTML:
<html>
<head>
<style type="text/css">
a { color: #000; }
body { background: #444; }
#mainlist { list-style: none; }
#mainlist li
{
float: left;
margin-left: 10px;
border-top: 1px solid black;
border-left: 1px solid black;
border-right: 1px solid black;
padding: 10px;
background: #aaa;
display: inline;
}
#sublist
{
background: #aaa;
border: 1px solid black;
width: 100px;
display: none;
position: absolute;
list-style: none;
margin: 0px;
padding: 0px;
margin-left: -11px;
}
#sublist li
{
border: none;
background: #aaa;
width: 100%;
text-align: left;
}
#sublist li:hover { background: #ccc; }
#mainlist li:hover { z-index: 60; }
/* When mainlist li is hovered show the sublist */
#mainlist li:hover > #sublist
{
z-index: 50;
display: block;
}
</style>
</head>
<body>
<ul id="mainlist">
<li><a href="#">Testlink 1</a></li>
<li><a href="#">Testlink 2</a>
<ul id="sublist">
<li>Test 1</li>
<li>Test 2</li>
</ul>
</li>
</ul>
</body>
</html>
You can do it by tweaking your CSS slightly. Currently your top level <li>
's are styling your main items. There's no way to get these to appear above the #sublist
because the #sublist
is a child of them (you can't put a child of an element behind its parent).
The fix is to apply the top level item styles on the <a>
tags. These are siblings of the #sublist
and so stacking them with z-index is easy:
As a simple demonstration, add this rule to your CSS and you'll see the #sublist
is now below the <a>
:
#mainlist li a {
padding: 10px;
background: red;
position: relative;
z-index: 60;
}
All you have to do is transfer all the #mainlist li
CSS rules to #mainlist li a
.
精彩评论