How to Create a Horizontal Hierarchical Menu Using HTML And CSS

I am planning to write a series of articles on creating menus in various ways and this is the first one in the series. This article will explain how to create a simple 2-level menu using HTML and CSS only.

We know there are many of ways to create a HTML menu but at times, we need to use only HTML/CSS in the project to create a nice menu. So, let's get started.

We will create a HTML structure as below using <ul> and <li> tags. Write the following code in your HTML file where you want to place the menu.

<div class="menu">

    <ul>

        <li><a href="#">Menu 1</a></li>

        <li><a href="#">Menu 2</a>

            <ul>

                <li><a href="#">Menu 2.1</a></li>

                <li><a href="#">Menu 2.2</a></li>

                <li><a href="#">Menu 2.3</a></li>

            </ul>

        </li>

        <li><a href="#">Menu 3</a>

            <ul>

                <li><a href="#">Menu 3.1</a></li>

                <li><a href="#">Menu 3.2</a></li>

                <li><a href="#">Menu 3.3</a></li>

            </ul>

        </li>

    </ul>

</div>

Now, we have the structure ready. Definitely, the current menu does not look good and we will now apply some CSS to make it look beautiful. Write the following code in the <head> section.

<style type="text/css">

    .menu

    {

        width: 500px;

        margin: 0px auto;

        font-family: Arial, Helvetica, sans-serif;

        font-weight: bold;

        font-size: 14px;

    }

    .menu ul li a:link, div ul li a:visited

    {

        display: block;

        background-color: #f1f1f1;

        color: #000;

        text-align: center;

        text-decoration: none;

        padding: 4px;

        border-bottom: 1px solid #fff;

        width: 150px;

    }

    .menu ul li a:hover

    {

        background-color: #ccc;

    }

    .menu ul li ul li a:link, li ul li a:visited

    {

        display: block;

        background-color: #f1f1f1;

        color: #000;

        text-align: center;

        text-decoration: none;

        padding: 4px;

        border-bottom: 1px solid #fff;

        width: 150px;

    }

    .menu ul li ul li a:hover

    {

        background-color: #ccc;

    }

    .menu ul

    {

        list-style-type: none;

        margin: 0px;

        padding: 0px;

    }

    .menu ul li

    {

        float: left;

        margin-left: 5px;

    }

    .menu ul li ul li

    {

        float: none;

        margin-left: 0px;

    }

    .menu ul li ul

    {

        display: none;

    }

    .menu li:hover ul

    {

        display: block;

    }

</style>

Save the HTML file and double-click on it to view in the browser. Your menu should look something like the following screenshot.

menu

You can read other parts of this series below:

I hope you like this article! Cheers!

Up Next
    Ebook Download
    View all
    Learn
    View all
    Think. Innovate. Grow.