Chris Wakeling Chris Wakeling - 4 months ago 18
HTML Question

creating a hierarchy like menu

I'm trying to make a navigation bar with drop down menus for each item, I understand there needs to be visibility and what not in CSS but I'm unsure how to do it.

Just to be clear id want something like




Food | Houseware | Toys
-----
Breakfast
Lunch
Dinner
Snack > Orange
banana
apple





<section id="navbar">
<ul>
<li><a href=#> Food </a></li>
<li><a href=#> Houseware
<ul>
<li><a href=#> Breakfast </a></li>
<li><a href=#> Lunch </a></li>
<li><a href=#> Dinner </a></li>
<li><a href=#> Snacks </a></li>
</ul>
</a></li>
<li><a href=#> Toys </a></li>
</ul>
</section>


This is the code I have at the moment and it creates the bar along the top but the "Breakfast dinner lunch snacks" bit I'm guessing needed to be hidden until
:hover
is used on each particular
<li>
. I guess my round about question is am I right in putting a list within a list? If so could someone then explain the concept of what to use to make it hidden until hovered over (also if possible to make sure it snaps to the right of the drop down menu as another menu).

Any help would be greatly appreciated.

Answer

As said by BLOOD-BATH use the ">" selector to select the immediate children which will be helpful in styling the sub menu items. For eg: when you add styles to #navbar > ul > li, it applies the styles to the li items Food, Houseware, Toys.

To hide the sub menu items initial, make the submenu items display:none and on hover make them display:block. Use position:absolute on the sub menu items.

This fiddle might help you.

HTML

<section id="navbar">
    <ul>
        <li><a href="#"> Food </a></li>
        <li><a href="#"> Houseware 
            <ul>
                <li><a href="#"> Breakfast </a></li>
                <li><a href="#"> Lunch </a></li>
                <li><a href="#"> Dinner </a></li>
                <li><a href="#"> Snacks </a>
                    <ul>
                        <li><a href="#">Orange</a></li>
                        <li><a href="#">Banana</a></li>
                        <li><a href="#">Apple</a></li>
                    </ul>
                </li>
            </ul>
            </a></li>
        <li><a href=#> Toys </a></li>
    </ul>
</section>

CSS

ul{
    list-style:none;
    padding:0;
}

ul li{
    position:relative;
}

#navbar > ul > li{
    display:inline-block;
    background-color: #ccc;
}

#navbar ul ul{
    display:none;
    position:absolute;
    top:100%;
    background-color:#fadde8;
}

#navbar ul li:hover > ul{
    display:block;
}

#navbar ul ul ul{
    top:0;
    left:100%;
    background-color:#71efd3;
}
Comments