How to use only the CSS In Javascript

In this approach, the dropdown functionality is achieved using only CSS without the need for JavaScript. This is done by utilizing the :hover pseudo-class to toggle the visibility of the dropdown menu content.

Example: The below code implements the CSS properties to create a dropdown menu.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,
                                   initial-scale=1.0">
    <style>
        .dropdown {
            left: 40%;
            text-align: center;
            position: relative;
            display: inline-block;
        }
 
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
            min-width: 160px;
            z-index: 1;
        }
 
        .dropdown:hover .dropdown-content {
            display: block;
        }
 
        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
 
        .dropdown-content a:hover {
            background-color: #f1f1f1;
        }
    </style>
</head>
 
<body>
    <div class="dropdown">
        <h1 style="color: green;">
            w3wiki
        </h1>
        <h2>
            Hover the below text to see the
            <br/>content of the dropdown menu.
        </h2>
        <span>
            Toggle Dropdown
        </span>
        <div class="dropdown-content">
            <a href="#item1">Item 1</a>
            <a href="#item2">Item 2</a>
            <a href="#item3">Item 3</a>
        </div>
    </div>
</body>
 
</html>


Output:

How to Create a Dropdown Menu with CSS & JavaScript ?

A dropdown menu is a common user interface element that allows users to select from a list of options. It is often used in navigation bars or forms to conserve space and provide a clean user experience. Creating a dropdown menu involves a combination of CSS for styling and JavaScript for interactivity.

There are several approaches to creating dropdown menus, but two common methods are:

Table of Content

  • Using only the CSS
  • Using JavaScript and CSS

Similar Reads

Using only the CSS

In this approach, the dropdown functionality is achieved using only CSS without the need for JavaScript. This is done by utilizing the :hover pseudo-class to toggle the visibility of the dropdown menu content....

Using JavaScript and CSS

...

Contact Us