Creating a Bootstrap 4.1 dropdown submenu on hover: A step-by-step guide

Currently, I am developing a website and I am looking to implement a dropdown submenu on hover using Bootstrap 4.1.

Here is the HTML code snippet I have utilized to create the hover dropdown menu:

<div class="navbar-collapse text-center" id="navbarResponsive">
  <ul class="navbar-nav ml-auto">

    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      main menu
    </a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" href="#">A</a>
        <a class="dropdown-item" href="#">B</a>
        <a class="dropdown-item" href="#">C</a>
        <a class="dropdown-item" href="#">D</a>
      </div>
    </li>

    <button type="submit" onclick="location.href='/M';" class="btn btn-default">R</button>

  </ul>
</div>



Question:

I am looking for suggestions on modifying the code above to display dropdown items E, F, G, H on hover of item D.

Answer №1

Here is a solution that may assist you...

.dropdown:hover>.dropdown-menu {
  display: block;
}
.dropdown-item:hover>.dropdown-menu {
  display: block;
}
ul li{
list-style-type:none;
display: inline;
}

.navbar-nav .nav-link{display:inline-block;}
   
.ml-auto {display:inline-block!important;}

.dropdown>.dropdown-toggle:active {
  pointer-events: none;
}
<!doctype html>
<html lang="en>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">

  <title>Dropdown submenu on hover</title>
</head>

<body>

  <div class="navbar-collapse text-center" id="navbarResponsive">
    <ul class="navbar-nav ml-auto">
 <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Main menu
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">A</a>
          <a class="dropdown-item" href="#">B</a>
          <a class="dropdown-item" href="#">C</a>
          <a class="dropdown-item nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          D
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">E</a>
          <a class="dropdown-item" href="#">F</a>
          <a class="dropdown-item" href="#">G</a>
          <a class="dropdown-item" href="#">H</a>
        </div>
        </div>
      </li>
    </ul>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
</body>

</html>

Answer №2

Check out this CodePen link for the answer you're looking for: link

Simply create a structure like this

<li>
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">D <b class="caret"></b></a>
    <ul class="dropdown-menu multi-level">
        <li><a href="#">E</a></li>
        <li><a href="#">F</a></li>
        <li><a href="#">G</a></li>
        <li class="divider"></li>
        <li class="dropdown-submenu">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">H</a>
            <ul class="dropdown-menu">
                <li><a href="#">I</a></li>
                <li><a href="#">J</a></li>
                <li><a href="#">K</a></li>
            </ul>
        </li>
    </ul>
</li>

The complete code is available in the CodePen link provided above in this response.

Answer №3

To implement the desired functionality, you just need to include the following CSS code.

.dropdown:hover>.dropdown-menu {
  display: block;
}

.dropdown>.dropdown-toggle:active {
  pointer-events: none;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">

  <title>Dropdown submenu on hover</title>
</head>

<body>

  <div class="navbar-collapse text-center" id="navbarResponsive">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          main menu
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">A</a>
          <a class="dropdown-item" href="#">B</a>
          <a class="dropdown-item" href="#">C</a>
          <a class="dropdown-item" href="#">D</a>
        </div>
      </li>
      <button type="submit" onclick="location.href='/M';" class="btn btn-default">R</button>
    </ul>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
</body>

</html>

Answer №4

  1. To begin, start by creating a new CSS file with any name you prefer. For example, I named mine "personal_style.css".
  2. Now, link this file to your webpage after the Bootstrap link. Your code should look similar to the example below:

    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="personal_style.css">
    
  3. Next, add the snippet below to your custom CSS file. Remember not to modify the original Bootstrap file to avoid complications during updates.

li.dropdown:hover > .dropdown-menu {
    display: block;
}

Answer №5

If you're designing for mobile, consider using the :hover style within a media query to make elements clickable. See the example below:

/* ============ mobile view ============ */
@media all and (max-width: 991px) {
    .navbar .nav-item .dropdown-menu{ display: none; }
    .navbar .nav-item:hover .nav-link{ color: #fff;  }
    .navbar .nav-item:hover .dropdown-menu{ display: block; }
    .navbar .nav-item .dropdown-menu{ margin-top:0; }
}   
/* ============ mobile view .end// ============ */

You can also enhance user experience by adding fade animation. Check out this code for more details:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to insert text onto an Isotope image?

I recently created a portfolio using Isotope and Jquery, but I am struggling to add descriptive text to my images without disrupting the layout of the portfolio. I have experimented with various options such as using position:relative for the images and p ...

Opacity for ghost images in HTML5 drag-and-drop interface

Is there a way to make the ghost image for draggable elements in Chrome render on a transparent background, similar to how Firefox does it? I'm seeing that in Chrome (Chromium 45), the ghost image is displayed on a white background. For Example: http ...

Is it possible to create a webpage where the header and footer remain static, while the content in the body can be dynamically changed

I am in the process of creating a webpage where main.html will load a page with a static header and footer that remains unchanged when navigation links are clicked. I'd like to achieve this using Javascript, with the body content being sourced from an ...

Issue with Submit Button Functionality in Django Form Submission

I'm currently facing an issue with an HTML template I built using Bootstrap. My problem lies in the fact that I have a JavaScript function that dynamically adds rows to a Django form with specific fields whenever I need to. However, when I add a row, ...

A guide on switching the status of various inputs in a table based on the selection of a radio button

In the scenario below, let's consider the following HTML structure: <tr> <td> <label for="c1_testRdio">Have you taken any tests in this class?:</label> <br> <label>Yes<input type="rad ...

Utilize a unique CSS selector and content property to insert a space character between two inline-block elements

I have a group of connected span elements with the class tag from bootstrap v4. Because they are generated from a react.js array of JSX elements, they sit adjacent to each other without any spacing between them: <span class="tag tag-primary">text< ...

How can one set relative paths for links when including a file from a different directory that contains links?

My project directory is structured as follows: root css img src login login.php dashboard basic header.php footer.php profile.php manage.php department ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Can someone please explain the purpose of row-sm and row-cols-sm-n (where n<12)? I've come across the col-sm-n (where n<12) but I'm unsure about how row-sm is used

From my understanding, when using col-sm-n in Bootstrap, the columns in a row will stack on top of each other when the device screen width is less than the specified size for sm. But what about row-sm? Does it function similarly to col-sm? And what exactly ...

Items in the Vue.Draggable display can be arranged on both the left and right

Recently delving into Vue.js, I am utilizing Vuedraggable for item dragging in my project. Currently, the items in the draggable div are shown as Text 1 Text 2 Text 3 Text 4 Is there a way to rearrange them to display like this? Text 1 Text 2 Text 3 T ...

Tips for utilizing ng-model in an Angular application

<input type="search" placeholder="{{'COMPONENT_PROPERTIES.SEARCH_ICON' | translate}}" ng-model="icon.name" list="classIcon" ng-change="changeFn(icon.name)"> <i class="{{$select.selected}}"></i> &nbsp;&nbsp; {{$s ...

Is there a way to create distance between these icons?

<div id="unique-icons"> <a href="#"> <img class="github-logo1" src="GitHub-Mark-64px.png" alt="first github logo"> </a> <a href="#"> <i ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

Tips for enabling background scrolling when Popover is displayed: (React, React Native, Native-Base)

I'm utilizing the Popover component from NativeBase to design my popover: const SettingsButton: React.FC<Props> = () => { return ( <Popover trigger={(triggerProps) => { return ( ...

What is the best way to format a `<ul>` element that does not contain any `<li>` elements?

A new feature on my website allows users to dynamically add list items (<li>) to a list container (<ul>). I want the list container style to change when there are no list items present. <ul class="con"> </ul> ul.con:not(: ...

Obtain the outcome of HTML5 FileReader by utilizing promises within an asynchronous function

I am encountering a challenge in my Angular 4 application where I am working with an image. I am trying to pass the base64 string to another variable, but due to the asynchronous nature of this process, the image.src ends up being empty. As a result, the ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

Text animation that rises smoothly within a concealed overflow region

I'm currently trying to replicate the effect seen in this example: Specifically, I am referring to the text that reads "CREATIVE AGENCY FOR DARING BRANDS" Although it appears simple, I am having trouble figuring out how to achieve it. I primarily wo ...

What is the method for obtaining the width of a g element?

I am encountering an issue with retrieving the width of the <g></g> element using jQuery. Both .innerWidth() and width() methods are returning null for me. Is there a way to obtain the width of the <g></g> element using jQuery? I a ...

When it comes to assigning a background to a div using jQuery and JSON

I have been experimenting with creating a database using only JSON and surprisingly, it worked once I added a "js/" in the URL. However, my current issue lies with CSS. Let me elaborate. Here is the JSON data: [ { "title":"Facebook", ...