Create a dropdown menu with Bootstrap 4 that pushes a popup below the navigation bar

I've incorporated a drop-down menu into my Bootstrap 4 navbar, but I'm facing an issue with its positioning. Instead of having the drop-down menu appear below the navbar as intended, it shows up somewhere else due to the default top attribute value being set to 100%. To address this, I adjusted the top attribute to a custom value to align the drop-down menu just beneath the navbar. If anyone has a more efficient solution to achieve this alignment without resorting to custom values, I'd appreciate your input.

The modification I made has caused another problem – whenever I try to move the cursor from the menu link to the drop-down menu, the menu disappears. This behavior occurs because the menu is triggered by hovering, not clicking. The images below illustrate this issue:

https://i.sstatic.net/JfxLF.png https://i.sstatic.net/ebBjB.png

This is my current navbar setup (to experience the issue, you need to view the desktop version):

.navbar-brand p {
    width: auto;
    max-width: 170px;
    height: 47px;
}

.navbar {
    padding: .25rem 1rem;
}

.nav-item {
    padding: 0px 10px;
}

.navbar .nav-item:first-child {
    padding-left: 0px;
}

.nav-item:last-child {
    padding-right: 0px;
}

.burger-menu {
    justify-content: right;
}

.dropdown-menu {
    left: unset !important;
    min-width: 300px !important;
    top: 3.1rem !important;
}

.dropdown:hover > .dropdown-menu {
    display: block;
}
.dropdown > .dropdown-toggle:active {
    pointer-events: none;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b6a9b6b6a3b4e8acb586f7e8f7f0e8f6">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-white">
  <div class="container">
    <div class="d-flex flex-grow-1">
      <span class="w-100 d-lg-none d-block"><!-- hidden spacer to center brand on mobile --></span>
      <a class="navbar-brand" href="#">
        <p>My Image</p>
      </a>
      <div class="w-100 d-flex burger-menu">
        <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#myNavbar7" aria-expanded="false">
                <span class="navbar-toggler-icon"></span>
            </button>
      </div>
    </div>
    <div class="navbar-collapse flex-grow-1 collapse" id="myNavbar7" style="">
      <ul class="navbar-nav ml-auto flex-nowrap">
        <li class="nav-item">
          <a href="#" class="nav-link">Link1</a>
        </li>
        <li class="nav-item">
          <a href="#" class="nav-link">Link2</a>
        </li>
        <li class="nav-item">
          <a href="#" class="nav-link">Link3</a>
        </li>
        <li class="nav-item dropdown">
          <a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown">Menu</a>
          <div class="dropdown-menu">
            <div class="row">
              <div class="col-xl-12">
                <a href="" class="nav-link">All Categories</a>
              </div>
              <div class="col-xl-6">
                <a href="#" class="dropdown-item">link</a>
                <a href="#" class="dropdown-item">link</a>
                <a href="#" class="dropdown-item">link</a>
                <a href="#" class="dropdown-item">link</a>
              </div>
              <div class="col-xl-6">
                <a href="#" class="dropdown-item">link</a>
                <a href="#" class="dropdown-item">link</a>
                <a href="#" class="dropdown-item">link</a>
                <a href="#" class="dropdown-item">link</a>
              </div>
            </div>
          </div>
        </li>
        <li class="nav-item">
          <form>
            <div class="input-group">
              <input type="text" class="form-control border border-right-0" placeholder="Search...">
              <span class="input-group-append">
                        <button class="btn btn-outline-dark border border-left-0" type="button">
                            <i class="fa fa-search"></i>
                        </button>
                         </span>
            </div>
          </form>
        </li>
        <li class="nav-item">
          <a href="#" class="btn btn-secondary">Login</a>
        </li>
        <li class="nav-item">
          <a href="#" class="btn btn-primary">Register</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

Answer №1

Here is a way to achieve the desired effect using JavaScript:

Check out this example on CodePen

If you prefer not to use JavaScript, you can make the dropdown menu appear by adding the following CSS at the end of the menu link:

.dropdown:hover > .dropdown-menu {
    display: block;
    margin-top: -10px;
}

If this solution works for you, consider adding a custom class to the dropdown menu and then override the existing class with your custom styles.

https://i.sstatic.net/F1Lj8.jpg

By implementing these changes, you can position the dropdown where the menu ends and have it appear when hovering over the menu.

Answer №2

To achieve the desired effect, ensure to eliminate padding from .navbar and remove margin-top from .dropdown-menu. However, reserve the hover effect exclusively for desktop display sizes. Implement a media query similar to the following:

/* ============ desktop view ============ */
@media all and (min-width: 992px) {
    .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; }
}   
/* ============ desktop view .end// ============ */

If you want more information on creating responsive navbars using Bootstrap, visit this tutorial link:

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

What is the best way to match the minimum height of one div to the height of another div?

I need to dynamically set the minimum height of #wrapper equal to the height of #sidebar, but the height of #sidebar is not fixed. Here is my attempt at achieving this with JavaScript: var sidebarHeight = jQuery('#sidebar').height; jQuery(&apos ...

ar.js varying mesh aspect ratios between Desktop and Mobile platforms

Currently facing a small issue with the aspect ratio difference between my desktop and mobile versions. Here is the desktop version: https://i.sstatic.net/dCyqQ.png And this is the mobile version: https://i.sstatic.net/PHas1.jpg Clearly, there is a notic ...

Centering the date vertically in JQuery Datepicker

I'm currently customizing the appearance of the jQuery datepicker, but I'm facing difficulty in aligning the dates vertically at the center. Here's the progress I've made so far: https://jsfiddle.net/L4vrkpmc/1/ Since the datepicker i ...

Exploring the Spacing Between ng-repeat Items in Angular

Encountering an issue with multiple ng-repeat elements displaying div elements as inline-block. A strange gap appears between the elements when transitioning from one ng-repeat to the next, which is visible in the provided image: A demonstration of this p ...

Assistance in configuring Zurb Foundation 5 for optimal integration with Laravel

As a relatively new user to Laravel with previous experience using older versions of Foundation, I am currently in the process of setting up a new Laravel project. My goal is to integrate the Foundation framework into my project, but I find myself a bit co ...

What is the best way to incorporate keyboard shortcuts into carousel operations using jQuery?

The example can be found here. I want to be able to navigate through the images using the left and right arrows on my keyboard. How can I achieve this using jQuery or CSS? This is the structure of the HTML: <div id="slider-code"> <a cla ...

When I click on a link to redirect it, I am confronted with a bizarre rectangle that

When attempting to create redirects using images, I encountered a small issue. Take a look at this screenshot: https://i.sstatic.net/LgStu.pnghttps://i.sstatic.net/eEnNB.png This is the item in question: <p><div><a title="Home" hr ...

What are some ways to utilize v-on="$listeners" besides just for @click events?

My Button.vue component has a specific structure. I am utilizing v-on="$listeners" to transfer all listeners to the <a> element. <template> <a v-bind="$attrs" v-on="$listeners" class= ...

Sorting depth based on z-index in a three.js render depth algorithm

My current project involves rendering planes with textures and sprites, all of which have transparent PNG textures. However, I've noticed a problem with transparency when objects overlap. I attempted to capture a screenshot of the issue for reference ...

Managing arrayBuffer in hapi.js: A Comprehensive Guide

I am struggling to upload an arrayBuffer to my server and save it to a file. On the client side, I am using axios, and on the server side, I have implemented Hapi js. However, I am facing difficulties in extracting data from the request in the Hapi handler ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

The text alongside the radio button is not aligned vertically

Hello, I am attempting to vertically align text next to my radio button but encountering some issues. .radio { cursor: pointer; display: inline-flex; } .cui-a-radio-button__input { display: none; } .cui-a-radio-button__input:disabled + .cui-a-rad ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

Choose the descendant element of the element that has a specific attribute

One of the issues I am facing is related to a button with a span tag inside for the text. Occasionally, this button might be disabled, and my goal is to have it appear grey when in that state. However, I am encountering difficulties making this work proper ...

Adjusting Column Order in Bootstrap 4 for Responsive Screen Sizes

For my website, I envision having a layout where, on medium-sized screens and larger, there is a phone on the right side and text on the left. However, if the screen size is smaller than medium, I would like the text to move below the phone. <section i ...

Difficulty in selecting an item from a list of array

Encountering an issue when attempting to create a custom select drop-down list. When utilizing an array list in the map(), everything functions correctly. However, upon pressing enter, an item in the input field appears as [object Object]. Despite numerous ...

Is it possible to design a Controller and View that can manage the creation of one-to-many objects, specifically a single "container" object along with an unlimited number of "content"

One of the functionalities for users on the website will be the ability to create documents made up of chapters in a one-to-many relationship. Traditionally, this would involve creating separate views for chapter and document creation. How can I develop ...

Unable to apply nativeElement.style.width property within ngOnChanges lifecycle method

My current task involves adjusting the width of containers while also monitoring changes in my @Input since the DOM structure is dependent on it. @Input('connections') public connections = []; @ViewChildren('containers', { read: Elemen ...

Only incorporate the Angular service into the controller when it is necessary

When attempting to incorporate lazy loading for angular services, controllers, directives, and filters, I discovered a way to achieve something similar using RequireJS. However, I am struggling to find a way to dynamically load a service into a controller ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...