The Bootstrap Navbar features the brand on the left, collapsible icons in the center, and a single item positioned

I have been attempting to achieve this for two days now without any success. I have tried various codes from other questions posted here, but nothing seems to work. My goal is to have my navbar-brand on the left, some icons in the center, and one icon on the right, all of them collapsible. Despite trying everything, I couldn't get the flexbox to work with the collapsible div. The only solution that got me closer to my goal was:

<nav class="navbar navbar-expand-lg bg-bee navbar-bee justify-content-between" role="navigation">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler ml-auto" type="button" data-target="#navegador" data-toggle="collapse" aria-label="Expandir navegador" aria-expanded="false">
    <span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-nav">
    <a data-toggle="tooltip" data-placement="bottom" title="Buy" class="d-none d-lg-block nav-item nav-link rounded" href="#"><span class="far fa-handshake icon-nav"></span></a>
    <a data-toggle="tooltip" title="Sell" class="d-none d-lg-block nav-item nav-link rounded" href="#"><span class="fas fa-hand-holding-usd icon-nav"></span></a>
    <a data-toggle="tooltip" title="My Cart" class="d-none d-lg-block nav-item nav-link rounded" href="#"><span class="fas fa-shopping-cart icon-nav"></span></a>
</div>
<div class="navbar-nav">
    <form id="form-iSesion" action="procesos.php" method="POST">
        <a data-toggle="tooltip" title="Login or Register" id="iSesion" class="d-none d-lg-block nav-item nav-link rounded" href="#"><span class="fas fa-user icon-nav"></span></a>
        <input type="hidden" name="menu" value="1">
    </form>
</div>
</nav>

Resulting in:

Full display

Responsive behavior

However, when I activate the collapsible navbar, everything becomes disordered again because the container takes up a lot of space, and nothing I've tried fixes it.

Disordered view

If I add a background, you can see how much space it's consuming.

Collapsible with background

I'm at a loss for what else to attempt; this is driving me crazy.

EDIT: ZimSystem's solution works, but there's an issue. When the items collapse, each one takes up an entire row. I want them to display inline when the menu collapses, possibly by showing all of them horizontally.

Answer №1

If you're looking to implement a responsive Navbar using Bootstrap 4, one approach is to separate the elements within the navbar-collapse, assign specific widths to each Navbar section with w-* classes, and then make use of toggler buttons to expand and collapse the desired sections.

<nav class="navbar navbar-expand-lg bg-light navbar-light" role="navigation">
    <a class="navbar-brand w-25" href="#">Brand</a>
    <button class="navbar-toggler" type="button" data-target=".navbar-collapse" data-toggle="collapse" aria-label="Expand Navigation" aria-expanded="false">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse w-50" id="navigation">
        <div class="navbar-nav mx-auto justify-content-center">
            <a data-toggle="tooltip" data-placement="bottom" title="Buy" class="nav-item nav-link rounded" href="#"><span class="far fa-handshake icon-nav"></span></a>
            <a data-toggle="tooltip" title="Sell" class="nav-item nav-link rounded" href="#"><span class="fas fa-hand-holding-usd icon-nav"></span></a>
            <a data-toggle="tooltip" title="My Cart" class="nav-item nav-link rounded" href="#"><span class="fas fa-shopping-cart icon-nav"></span></a>
        </div>
    </div>
    <div class="collapse navbar-collapse w-25" id="navigation2">
        <form id="form-login" class="navbar-nav w-100  justify-content-end" action="process.php" method="POST">
            <a data-toggle="tooltip" title="Login or Register" id="login" class="nav-item nav-link rounded" href="#"><span class="fas fa-user icon-nav"></span></a>
            <input type="hidden" name="menu" value="1">
        </form>
    </div>
</nav>

https://www.example.com/code-sample

Answer №2

Below is a basic example utilizing Bootstrap v4 to achieve the requested functionality. The "center" menu is centered between the logo and right menu by applying the ml-auto mr-auto classes to the middle element, which sets the left and right margins to auto for center alignment.

If you desire a perfectly centered layout within the browser window, one option is to ensure the brand and right menu have equal widths within their parent container. This can be achieved by taking them out of the standard flow using position:absolute, but it necessitates manual positioning with properties like top/left/right to prevent overlap with the center menu on various screen sizes.

An alternative approach involves adding margin to adjust the width of the smaller element to match the larger one. In the provided example, a right margin of 22px was added to the logo to balance its size against the right menu (86.25 - 64.48):

@media (min-width: 992px) {
  nav .navbar-brand {
    margin-right: 22px;
  }
}

/* THE FOLLOWING CSS IS DEMONSTRATIVE AND NOT ESSENTIAL */

@media (min-width: 992px) {
  nav:after {
    width: 3px;
    content: '';
    position: absolute;
    background-color: red;
    height: 100px;
    left: 50%;
    transform: translateX(-50%);
    top: 100%;
  }
}


@media (min-width: 992px) {
  .navbar-nav.ml-auto.mr-auto {
    position: relative;
  }
  .navbar-nav.ml-auto.mr-auto:after {
    width: 1px;
    content: '';
    position: absolute;
    background-color: black;
    height: 50px;
    left: 50%;
    transform: translateX(-50%);
    top: 100%;
    z-index: 1;
  }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<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.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>


<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav ml-auto mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#">Some link</a>
      </li>
    </ul>
  </div>
</nav>

To dynamically handle this layout adjustment in JavaScript:

(function($) {
  let centerMenu = function() {
    let $left = $('.navbar-brand'),
      $right = $('.navbar-nav', 'nav').last(),
      hasWidth = function(e) {
        return e.is('*') && e.width() > 0
      }

    if (hasWidth($left) && hasWidth($right) && $(window).width() > 992) {
      if ($left.width() > $right.width()) {
        $right.css({
          marginLeft: ($left.width() - $right.width()) + 'px'
        });
      } else {
        $left.css({
          marginRight: ($right.width() - $left.width()) + 'px'
        })
      }
      $(window).off('load resize', centerMenu);
    }
  };
  $(window).on('load resize', centerMenu);
})(jQuery)

Check out jsFiddle.

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

Foundation 6: Conceal the Top Bar upon Clicking a Link

I'm currently working with Foundation 6 on a single-page website. Utilizing the Top Bar feature to navigate users to different sections of the site. However, I have run into an issue with the mobile version. When clicking a link from the collapsed Top ...

Having trouble accurately referencing the domain across various servers

I have set up two servers for production - one for php files and the other for static (css, js) files. Within my config.php file: $path ="https://mystaticdomain.com/"; To simplify access to paths, I created a variable to store the path for css and js fi ...

Ways to adjust the content width within an iframe without altering the iframe's overall width

I need help with adjusting the width slider in my iframe. I want the width slider to control the content width within the iframe, not the actual width of the iframe itself. Essentially, I want to switch between mobile and desktop mode by resizing the con ...

Change the font weight to bold for the selected item in the Javascript menu, and

I am working on an ASP MVC application that includes a menu with JavaScript functionality to navigate between pages. Currently, when I click on a menu item, it becomes bold and remains bold even when another menu item is selected. This results in all menu ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

Having difficulty adjusting the size of open-iconic icons in Bootstrap

I recently added the open iconic plugin to my project and I'm trying to adjust the size of the icon. While the original library has a property to change the size, it doesn't seem to work with the Bootstrap version. Is there an alternative way to ...

Continuous navigation bar with jquery mobile

I'm attempting to implement a persistent Jquery Mobile navbar footer feature. I want it to be generated dynamically using Javascript, specifically for a PhoneGap application, rather than relying on PHP for template creation. The information reference ...

Customize button styles for disabled buttons in Bootstrap 4 using SASS

Currently, I am utilizing bootstrap4 and experimenting with changing button colors using SASS. Within my customized SCSS file, the code snippet looks like this... @import "node_modules/bootstrap/scss/bootstrap"; $theme-colors: ( "primar ...

SVG embedded directly into CSS is compatible with Chrome and Edge browsers, but unfortunately does not render correctly in Firefox

I'm having an issue with my code that displays icons. The GitHub icon isn't showing up on Firefox, but it works fine on Chrome and Edge. Surprisingly, the Google icon is working across all browsers! .github-icon { background-image: url("data ...

Creating interactive elements within Bootstrap 5 Popovers: A step-by-step guide

I've been attempting to include a button inside the Popovers in Bootstrap, but so far I have not been successful. Currently, I am using Bootstrap-Popover and my goal is to place a button inside the popover. HTML <div class="col-lg-4 mb-3 ser ...

What is the best way to align two icons (images) next to each other in a footer section?

I'm almost done with the final section of my homepage... the footer. Any tips on how to float two icons (images) side by side? I'm familiar with hover effects, just need help with positioning them correctly. Thank you! HTML <!DOCTYPE html& ...

Menu made with CSS that disappears when clicked

I designed a menu with the following structure: <div class="nav"> <div class="drnav"> <ul class="ulMenu"> <li> <div class="menuHeader">My Home</div> <div class= ...

Ways to align an inner circle in the middle using CSS

div.container{ border:2px dashed blue; position:relative; } span.parent{ display:inline-block; width:40px; height:40px; border:2px solid black; border-radius:50%; text-align: center; position:absolute; right:20px; top:10px; } span.ch ...

Having difficulty managing the responses of two separate <select> elements with images in jQuery

I recently started using online jQuery to manage images within the "select" element of my HTML code. However, I've encountered a problem where events on each individual "select" element are not being separated correctly. var selectedId = ""; ...

Unable to save canvas as an image due to tainted canvas in a React application

I encountered an error after the line containing canvas.toDataURL(). An error message stating "Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvas may not be exported" was displayed. Despite attempting to search for ...

The div element is failing to adjust its height correctly to match its parent container

I'm struggling to make the red border that wraps around the text extend all the way to the bottom of its parent div. Setting the height to 100% isn't achieving the desired effect, as it needs to match the height of the image. Tip: Try resizing y ...

PHP receiving empty data from Ajax form submission

I can't seem to get the form data to be sent to PHP using AJAX. When I dump the data on the PHP page, it just returns null values. My goal is to create a program where I can upload an image, crop it in a pop-up window, and then save the cropped image ...

Adjust the dimensions of polymer components (checkbox)

When attempting to adjust the size of the paper-checkbox, I experimented with changing the width and height properties in my CSS file. Additionally, I tried using transform: scale(2,2). The scale property resulted in blurriness, while adjusting the width ...

Get a calendar that displays only the month and year

I am looking to incorporate two unique PrimeFaces calendars on a single page. The first calendar will display the date, while the second one will only show the month and year. To achieve this, I have implemented the following JavaScript and CSS specifica ...

Tips for adding classes to both parent and child elements in dynamically loaded data via an ajax request

I am facing a challenge with jQuery as a beginner. I have been struggling for the past week to load data from a JSON array using an ajax call. I'm also using a swipe plugin to swipe and display all images on the same div, but I'm unsure of how to ...