Dropdown Menu with Submenu CSS HTML

时间:2016-03-04 17:52:49

标签: html css menu

I'm trying to create a dropdown menu with submenu that align with the parent items in HTML/CSS, but I'm having trouble getting the alignment right. Right now, the submenus just appear at the top of the list instead of at the same level as their parent.

Here's the fiddle code for what I'm talking about: https://jsfiddle.net/h96jda5h/

I think it has something to do with the CSS nav properties, but I'm not sure what:

#nav ul{ list-style-type:none; padding:0; margin:0; }
#nav ul li{ display:inline-block; }
#nav ul li:hover{ background-color:#FFF; }
#nav ul li a,visited{ display:block; padding:15px; text-decoration:none; }
#nav ul li:hover >ul{ display:block;}
#nav ul ul{display:none; position:absolute; background-color:#FFF; min-width:200px; }
#nav ul ul li{ display:block;}
#nav ul ul li:hover{ background-color:#F1F7F7; }
#nav ul ul li"hover > ul{ display: block; }
#nav ul ul ul{ margin: -52px 0 0 200px; background-color:#FFF; }

I searched this website for the answer and found help with the 'sub' class for li, but it doesn't appear to be working for me for some reason. Any advice would be so helpful! Thanks!

2 个答案:

答案 0 :(得分:0)

You're just missing one single css instruction:

position: relative

in here

#nav ul ul li{ display:block;}

Explanation:

Absolute positioned elements refer to the first parent that's absolute or relative positioned. Right now, the sub-menu was taking in consideration the ul and not the li

答案 1 :(得分:0)

You need to add position: relative to the absolutely positioned ul's parent li.

Absolutely positioned elements are positioned relative to their nearest ancestor. Any parent element with a position other than position: static (default) is considered an ancestor so adding position: relative to the li element makes it the closest ancestor of it's child ul.

http://learnlayout.com/position.html

https://css-tricks.com/absolute-positioning-inside-relative-positioning/

With your current example, you can do it like this.

.sub { position: relative; }

or like this

#nav ul ul li { 
  display:block;
  position: relative;
}

https://jsfiddle.net/h96jda5h/1/