How do I make the dropdown menu in a navbar stretch horizontally to cover the entire width of the page container?

When I hover over an item in the navbar, a horizontal dropdown menu currently opens as shown below (note the width of the dropdown menu): https://i.sstatic.net/824OVkWT.png

What am I aiming for?

I want to expand the horizontal dropdown menu like in the image below, but only on desktop version. I want the dropdown menu to be as wide as the container (the one Bootstrap already uses with the container class) that is used in my navbar and will also be used throughout the site body.

In the image (montage/collage), I'm inspecting the navbar with Chrome to highlight the navbar container and show you how wide I'd like the dropdown menu to be. https://i.sstatic.net/ANCfM18J.png

Can anyone assist me in achieving this? I've made several attempts, all unsuccessful.

document.addEventListener("DOMContentLoaded", function() {
  const dropdowns = document.querySelectorAll(".nav-item.dropdown");

  dropdowns.forEach(dropdown => {
    dropdown.addEventListener("mouseenter", function() {
      const menu = this.querySelector(".dropdown-menu-horizontal");
      if (menu) menu.style.display = "flex";
    });

    dropdown.addEventListener("mouseleave", function() {
      const menu = this.querySelector(".dropdown-menu-horizontal");
      if (menu) menu.style.display = "none";
    });
  });
});
* {
  box-sizing: border-box;
}

/* Navbar styles */

.navbar {
  background-color: #000033;
  padding: 0 !important;
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1000;
  box-sizing: border-box;
}

/* Brand logo and text styles */

.logo {
  height: 80px;
  margin-right: 10px;
}

.brand-text {
  color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: left;
  line-height: 1;
}

.fondazione {
  font-size: 0.80em;
  font-weight: normal;
  letter-spacing: 0.28em;
}

.surname {
  font-size: 2.4rem;
  font-weight: bold;
  letter-spacing: 0.05em;
}

/* Colored rectangle under navbar links */

.navbar-nav .nav-link {
  color: #ffffff;
  margin-right: 10px;
  padding: 0 10px;
  line-height: normal;
  position: relative;
  height: 100%;
  display: flex;
  align-items: center;
}

.navbar-nav .nav-link:hover::after {
  content: '';
  display: block;
  width: 100%;
  height: 3px;
  background-color: #459439;
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 1000;
}

/* Remove dropdown arrow */

.nav-link.dropdown-toggle::after {
  display: none;
}


/* Horizontal dropdown menu styling */

.dropdown-menu-horizontal {
  display: none;
  background-color: #000033 !important;
  padding: 20px !important;
  min-width: 100%;
  border-radius: 0;
  position: absolute;
  left: 0;
  top: 97% !important;
  z-index: 9999;
}

.dropdown-item-horizontal {
  color: #ffffff;
  display: inline-flex;
  align-items: center;
  padding: 10px 20px;
  margin-right: 30px;
  white-space: nowrap;
}

.dropdown-item-horizontal img {
  width: 50px;
  height: 50px;
  margin-right: 15px;
}

.dropdown-item-horizontal:hover {
  color: #d4d4ff;
  text-decoration: none;
}

.nav-item:hover .dropdown-menu-horizontal {
  display: flex;
  justify-content: space-around;
}

@media (max-width: 768px) {
  .navbar-expand-md .navbar-nav .nav-link {
    padding-top: 20px;
    padding-bottom: 20px;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">

<nav class="navbar navbar-expand-md navbar-dark mb-0">
  <div class="container align-items-stretch">
    <a class="navbar-brand d-flex align-items-center" href="#">
      <img src="img/..." alt="Logo" class="logo">
      <div class="brand-text">
        <span class="fondazione">AAAAAAA</span>
        <span class="surname">XXXX</span>
      </div>
    </a>
    <button class="navbar-toggler align-self-center" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ml-auto h-100">
        <li class="nav-item dropdown">
          ...
          <li class="nav-item"><a class="nav-link" href="#">Item 8</a></li>
      </ul>
    </div>
  </div>
</nav>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22414d504762100c31b05180907">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

Answer №1

To enhance the layout, apply the Bootstrap class position-relative to the container, and assign position-static to the dropdown.

Include the class w-100 for the dropdown-menu.

For a vertical view on mobile devices:

/* Mobile responsive design */
@media (max-width: 768px) {
   .navbar-expand-md .navbar-nav .nav-link {
       padding-top: 20px;
       padding-bottom: 20px;
   }

   .dropdown-menu-horizontal {
       flex-direction: column;
   }
}

document.addEventListener("DOMContentLoaded", function () {
    const dropdowns = document.querySelectorAll(".nav-item.dropdown");

    dropdowns.forEach(dropdown => {
        dropdown.addEventListener("mouseenter", function () {
            const menu = this.querySelector(".dropdown-menu-horizontal");
            if (menu) menu.style.display = "flex";
        });

        dropdown.addEventListener("mouseleave", function () {
            const menu = this.querySelector(".dropdown-menu-horizontal");
            if (menu) menu.style.display = "none";
        });
    });
});
* {
    box-sizing: border-box;
}

/* Navbar styles */
.navbar {
    background-color: #000033;
    padding: 0 !important;
    display: flex;
    align-items: center;
    position: relative;
    z-index: 1000;
    box-sizing: border-box;
}

/* Brand logo and text styling */
.logo {
    height: 80px;
    margin-right: 10px;
}

.brand-text {
    color: #ffffff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: left;
    line-height: 1;
}

.fondazione {
    font-size: 0.80em;
    font-weight: normal;
    letter-spacing: 0.28em;
}

.surname {
    font-size: 2.4rem;
    font-weight: bold;
    letter-spacing: 0.05em;
}

/* Colored rectangle under navbar links */
.navbar-nav .nav-link {
    color: #ffffff;
    margin-right: 10px;
    padding: 0 10px;
    line-height: normal;
    position: relative;
    height: 100%;
    display: flex;
    align-items: center;
}

.navbar-nav .dropdown {
    display: flex;
    flex-direction: column;
}

.navbar-nav .nav-link:hover::after {
    content: '';
    display: block;
    width: 100%;
    height: 3px;
    background-color: #459439;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 1000;
}

/* Remove dropdown arrow */
.nav-link.dropdown-toggle::after {
    display: none;
}

/* Horizontal dropdown style */
.dropdown-menu-horizontal {
    display: none;
    background-color: #000033 !important;
    padding: 20px !important;
    min-width: 100%;
    border-radius: 0;
    position: absolute;
    left: 0;
    top: 97% !important;
    z-index: 9999;
}

.dropdown-item-horizontal {
    color: #ffffff;
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    margin-right: 30px;
    white-space: nowrap;
}

.dropdown-item-horizontal img {
    width: 50px;
    height: 50px;
    margin-right: 15px;
}

.dropdown-item-horizontal:hover {
    color: #d4d4ff;
    text-decoration: none;
}

/* Show dropdown menu on hover */
.nav-item:hover .dropdown-menu-horizontal {
    display: flex;
    justify-content: space-around;
}

/* Mobile responsive */
@media (max-width: 768px) {
    .navbar-expand-md .navbar-nav .nav-link {
        padding-top: 20px;
        padding-bottom: 20px;
    }

    .dropdown-menu-horizontal {
        flex-direction: column;
    }
}
<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>

<body>


    <!-- Navbar with logo and links -->
    <nav class="navbar navbar-expand-md navbar-dark mb-0">
        <div class="container align-items-stretch position-relative">
            <a class="navbar-brand d-flex align-items-center" href="#">
                <img src="img/..." alt="Logo" class="logo">
                <div class="brand-text">
                    <span class="fondazione">AAAAAAA</span>
                    <span class="surname">XXXX</span>
                </div>
            </a>
            <button class="navbar-toggler align-self-center" type="button" data-toggle="collapse"
                data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto h-100">
                    <li class="nav-item dropdown position-static">
                        <a class="nav-link" href="#" id="foundationDropdown">COMPANY</a>
                        <div class="dropdown-menu dropdown-menu-horizontal w-100" aria-labelledby="foundationDropdown">
                            <a class="dropdown-item-horizontal" href="#"><img src="..." alt="Logo 1"> Example 1</a>
                            <a class="dropdown-item-horizontal" href="#"><img src="..." alt="Logo 2"> Example 2</a>
                            <a class="dropdown-item-horizontal" href="#"><img src="..." alt="Logo 3"> Example 3</a>
                        </div>
                    </li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 2</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 3</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 4</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 5</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 6</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 7</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Item 8</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6864796e4b3925322539">[email protected]</a>/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
</body>

</html>

Answer №2

To change the layout of the main menu item, you can adjust the CSS position property to 'static'. This will ensure that the positioning of the submenu is relative to the main navigation bar .navbar (which spans the full width), or in this specific case, the navbar container (.navbar .container) with a position:relative setting. Here are the necessary CSS adjustments for achieving this effect on desktop screens wider than 786px:

@media (min-width: 769px){
  .navbar .container{
    position: relative;
  }

  .navbar-nav > .nav-item{
    position: static;
  }

  .navbar-nav > .nav-item:first-child > div.dropdown-menu {
    margin-top: -1px;
    width: 100%;
  }
}

Edit: I also added position:relative to the .navbar .container to match the width of the navbar container.

document.addEventListener("DOMContentLoaded", function () {
    const dropdowns = document.querySelectorAll(".nav-item.dropdown");

    dropdowns.forEach(dropdown => {
        dropdown.addEventListener("mouseenter", function () {
            const menu = this.querySelector(".dropdown-menu-horizontal");
            if (menu) menu.style.display = "flex";
        });

        dropdown.addEventListener("mouseleave", function () {
            const menu = this.querySelector(".dropdown-menu-horizontal");
            if (menu) menu.style.display = "none";
        });
    });
});
* {
    box-sizing: border-box;
}

/* Rest of the CSS styles remain unchanged */
...

(Note: For optimal viewing experience, please use a desktop computer screen and click on Run Code Snippet, then 'Full page')

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

Looking for a feature similar to mix-blend-mode that can change the text color to its inverse when overlapping with a background color that matches

Seeking assistance on a Mondrian-style CSS Grid layout with a rotated sticky heading. Looking to achieve a visual effect where intersecting text turns white when a black horizontal line passes over or under it. https://i.sstatic.net/YQaxV.png Considering ...

flylatex is struggling to locate some modules

When I try to run flylatex from github on Debian and Ubuntu, I encounter the following Error. I'm not sure if there's an issue with my nodejs setup or if flylatex itself has an error. To troubleshoot, I initially ran npm install -d in the working ...

Navigating specific elements within ReactORTraversing designated components

Trying to iterate through specific elements in React to render a portion of an array for each view. The rendering of the array should start from ArrayIndexStart and end at ArrayIndexEnd. Here is the current implementation: const ObjectArray = [ {" ...

Display data only when the user interacts with the input field - AngularJs

I am currently working on a program that requires the input data to only show if the input field is touched once. Unfortunately, I am not getting the expected result as nothing is displayed in the span tag (and there are no errors in the console). Can some ...

What makes table layouts load pages more quickly?

Is it true that Google uses tables for layout because they load faster? I'm skeptical of this claim, as a CSS based layout with minimal and semantic markup seems like it would be more efficient in terms of page load time. It is commonly believed that ...

Is the menu item a little crooked?

Working on designing a menu, and I noticed that the 'Book Now' option is slightly misaligned (pushed down) after adding a border. This seems to disrupt the horizontal alignment. Is there a way to correct this issue? Check out my Codepen Here is ...

obtain every drop-down choice from Angular 2's selectiongetConfig() function

Within the document, there is a select element as shown below: <select tabindex="1" size="5" name="abc" multiple> <option value>Select a value.</option> <option value>option 1</option> <option value>option 2 ...

Combine arrays of JSON data within a JSON object using JavaScript

Looking for help with reformatting a JSON response {"result":[["abc","de"],["fgh"],["ij","kl"]]} Interested in transforming the response to: {"result":["abc","de","fgh","ij","kl"]} What's the best way to accomplish this task? ...

creating a translucent jqm collapsible widget

Looking to make a jquery mobile collapsible element transparent. Attempted the following style, but it did not work: background-color: rgba(0, 0, 0, 0.6); Check out the Fiddle When I try this: background: #557700; filter: alpha(opacity=30); filter: pr ...

What is the best way to handle JSON data in vue.js?

I am facing an issue with vue.js. I want to create a settings page on the server program that has XML data. I believe it can be achieved by following these steps : server | parse XML to JSON client | get JSON and read JSON client | edit JSON client | ...

Navigating to a new view in AngularJS following a successful authentication with Firebase

After successfully logging in and authenticating through Firebase, I am looking to direct users to a specific view. app.controller('PageCtrl', function ($scope, $location, $http ) { $scope.logIn = function(){ var email = $('#logi ...

What steps can you take to resolve the issue of FirebaseError: When collection() is expected to be a CollectionReference, DocumentReference, or FirebaseFirestore?

I'm currently working on integrating Firebase with next.js, and I've encountered an error in the console that reads: FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore B ...

Using Javascript, dynamically animate the text in the hero unit with fading in and out effects

I currently have a "Hero" unit with the following code: <div class="hero-unit"> <div class="container"> <h1>Dapibus Euismod Mollis</h1> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis ...

Is it possible to incorporate an HTML file using PHP?

I'm looking to add an external HTML file containing my navigation bars to all pages. I attempted using: <?php htmlentities(file_get_contents("include/navigation.html")); ?> However, nothing is displaying on the page. I've searched other ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

The issue of Ajax not refreshing the HTML content within a dynamically generated div using JavaScript

(using jQuery) 1) I have a JavaScript click event that generates a form with a dropdown and a div like the following: $('#closestDiv').on('click','.firstClick', function(event){ var pass = $(this).attr('data-pass' ...

Steps for launching individual posts in modal windows using Laravel 8

Whenever I click on a post, it retrieves post.blade.php and comment.blade.php and executes it within a bootstrap modal. The current job is encountering the following issues: Error in Inclusion I attempted to include post.blade.php in a modal connection ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

What is the best way to override a custom class-li element within another class-li?

I've just started learning HTML5 and CSS3, and I've encountered a challenge: Here is the code I have written so far: .custom-list ol { counter-reset: item; padding-left: 10px; } .custom-list li { display: block; } .custom-l ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...