Teaching how to create a mini-learn dropdown in CSS

css dropdown menu tutorial
10 November 2024

Creating a mini-learn dropdown or the same dropdown menu on websites is one of the attractive and practical features in user interface design. This dropdown allows users to see a list of sub-items related to the selected item by clicking on the main item. In this tutorial, we will show you how to create a dropdown using CSS. The structure of such dropdowns benefits from proper styling and some CSS features like :hover and display properties.

To create a simple dropdown, we will first create the HTML structure. This structure includes an unordered list where each item can have a submenu. With the help of CSS, we can keep this dropdown hidden and show it only when needed. Using the position feature in CSS can help to display the dropdown at the correct location.

One of the advantages of using CSS for creating dropdown menus is that we can add different effects to them without the need for JavaScript. By utilizing CSS transitions and animations, we can create smooth transitions to enhance the user experience. Managing these animations gives you the ability to integrate the dropdown seamlessly into the overall site design.

Below is an example of a dropdown created. This example includes a menu with main items and sub-items that appear when hovering the mouse over them. Additionally, I will provide the necessary CSS code for styling this menu.


<style>
  ul {
    list-style-type: none;
  }
  li {
    display: inline-block;
    position: relative;
  }
  li ul {
    display: none;
    position: absolute;
    top: 100%;
  }
  li:hover ul {
    display: block;
  }
</style>
<ul>
  <li>Menu Item 1
    <ul>
      <li>Sub Menu 1</li>
      <li>Sub Menu 2</li>
    </ul>
  </li>
  <li>Menu Item 2</li>
</ul>

Code Explanation for the Dropdown Menu

ul → All unordered lists have the style type: none, which prevents default bullets from showing.
li → The list items are displayed as inline-block, meaning they are arranged in a single line while retaining the ability to position themselves relatively with position: relative.
li ul → Sub-menus are initially hidden (display: none) and are positioned absolutely to appear directly under their parent list items.
li:hover ul → When hovering over the main menu item, the submenu appears.

FAQ

?

How can I create a simple dropdown menu without JavaScript?

?

How can I add animations to the dropdown menu?