CSS Dropdowns

Home / CSS / CSS Dropdowns

CSS Dropdowns


CSS-Dropdowns:

Dropdown menus in CSS are commonly used in navigation bars or forms to provide a list of options when a user interacts with a specific element (usually a button or link). Creating a basic CSS dropdown menu involves using CSS to hide and show a list of items when the user hovers over or clicks on a trigger element. Here's a step-by-step guide on how to create a simple CSS dropdown menu:

HTML Structure:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Dropdown Menu</title>
</head>
<body>
    <div class="dropdown">
        <button class="dropbtn">Dropdown</button>
        <div class="dropdown-content">
            <a href="#">Option 1</a>
            <a href="#">Option 2</a>
            <a href="#">Option 3</a>
        </div>
    </div>
</body>
</html>

CSS (styles.css):

<style>
    /* Style the dropdown container */
    .dropdown {
      position: relative;
      display: inline-block;
    }

    /* Style the dropdown button */
    .dropbtn {
      background-color: #4CAF50;
      color: white;
      padding: 10px;
      border: none;
      cursor: pointer;
    }

    /* Style the dropdown content (hidden by default) */
    .dropdown-content {
      display: none;
      position: absolute;
      background-color: #f9f9f9;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
      z-index: 1;
    }

    /* Style the dropdown links */
    .dropdown-content a {
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
    }

    /* Change link color on hover */
    .dropdown-content a:hover {
      background-color: #ddd;
    }

    /* Show the dropdown content when hovering over the dropdown container */
    .dropdown:hover .dropdown-content {
      display: block;
    }
  </style>

In this example:

We have a simple HTML structure with a div container for the dropdown, a button as the trigger element, and a div for the dropdown content.

CSS is used to style the dropdown container, button, and dropdown content. The dropdown content is initially hidden (display: none;).

When a user hovers over the dropdown container (.dropdown:hover), we change the display property of the dropdown content to block, making it visible.

We style the links inside the dropdown content, and they change color on hover.