Customize your Bootstrap 4 navbar to align on the right with a button that remains visible on mobile devices

I'm working on setting up a navbar with three elements. I want to have a left-aligned brand, a group of right-aligned links that will collapse on smaller screens, and an additional button that stays visible at all times.

To achieve the alignment of the button and links, I used the ml-auto class. This worked well on mobile devices (see 1st image), but on desktops, the button ends up above the links (as shown in the 2nd image). I attempted to use the btn-group class, but the button ended up merging with the links, which didn't look right (3rd image).

How can I ensure proper horizontal alignment of these elements?

I should mention that I do not want the button to be grouped with the other right links. I want it to remain visible even on small screens. While I've come across similar questions on SO, they all involve placing the right-aligned items in a collapsible group, which doesn't suit my needs.

You can test the code below using the w3school TryIt editor

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
   <a class="navbar-brand" href="#">Home</a>


<div class="ml-auto">
            <button class="btn btn-success">My Button</button>

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
              <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto"/>
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Right Link 1</a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Right Link 2</a>
                    </li>

                </ul>
        </div>
</nav>

Answer №1

Many of the solutions provided do not effectively address the issue and involve complex workarounds that are not in line with the intended use of Bootstrap 4 Navbar. These solutions often fail to display properly on mobile devices. It's important to note that the .row class should only be used for grid columns, and the grid is not supported as Navbar content

The solution is actually quite simple. The only adjustment required is to disable the flex-grow property (using flex-grow-0) applied to the navbar-collapse element. This enables the ml-auto class to correctly position the button on the right-hand side.

<nav class="navbar navbar-expand-sm bg-dark navbar-dark justify-content-end">
    <a class="navbar-brand" href="#">Home</a>
    <button class="btn btn-success ml-auto">My Button</button>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse flex-grow-0" id="navbarSupportedContent">
        <ul class="navbar-nav text-right">
            <li class="nav-item active">
                <a class="nav-link" href="#">Right Link 1</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="#">Right Link 2</a>
            </li>
        </ul>
    </div>
</nav>

If you want the links to align right on mobile, you can also add the text-right class to the navbar-nav.

Demo:



For further information, you may also refer to: Bootstrap 4 - Navbar items outside the collapse

Answer №2

I made some adjustments to your code. Check it out by viewing it on a fullpage and resizing the screen:

I included the d-sm-none class on the first button, added the justify-content-end class to your nav collapse, and introduced another button

<button class="btn btn-success  d-none d-sm-block">My Button</button>
within your nav collapse that will only be displayed when the screen size is sm or larger.

<!DOCTYPE html>
<html lang="en>
<head>
  <<title>Bootstrap Example</title>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js></script>
</head>
<body>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark>
   <a class="navbar-brand" href="#">Home</a>


<div class="ml-auto>
            <button class="btn btn-success d-sm-none>My Button</button>
             

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent>
              <span class="navbar-toggler-icon></span>
            </button>

            <div class="collapse navbar-collapse justify-content-end" id="navbarSupportedContent>
            <button class="btn btn-success  d-none d-sm-block>My Button</button>
                <ul class="navbar-nav ml-auto ">
                    <li class="nav-item active>
                        <a class="nav-link" href="#">Right Link 1</a>
                    </li>
                    <li class="nav-item active>
                        <a class="nav-link" href="#">Right Link 2</a>
                    </li>

                </ul>
        </div>
</nav>
<br>

<div class="container>
  <h3>Navbar Forms</h3>
  <p>Use the .form-inline class to align form elements side by side inside the navbar.</p>
</div>

</body>
</html>

Answer №3

Finally, I have discovered the solution! The key is to effectively utilize the grid system. Make sure to adjust the col classes based on your responsiveness needs (particularly in the navbar collapse section). Additionally, it's important to note that the button and collapse should not be grouped together as you desired, since enclosing them in the same div can lead to issues with collapse functionality on mobile screens. Hopefully, this information proves beneficial for you.

body { 
    padding-top: 105px; 
}

.collapse{
  justify-content:flex-end;
}
.text-nowrap {
    white-space: nowrap;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
... // Rest of the HTML code provided

Answer №4

Resolved the issue by adding a "row" class to the div, allowing them to stack horizontally. However, this caused some unexpected behavior when the collapsed button was pressed, shifting towards the middle. This was fixed by adding more left margin.

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
   <a class="navbar-brand" href="#">Home</a>


    <div class="row ml-auto">
            <button class="btn btn-success ml-auto">My Button</button>

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
              <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                  <ul class="navbar-nav mr-auto" />
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Right Link 1</a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Right Link 2</a>
                    </li>

                </ul>
        </div>
    </div>        
</nav>

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

Using Multiple SCSS Files to Reference a Centralized Style Sheet

I am currently developing a React application and facing an issue with my SCSS files. I have three SCSS files, one main file that contains theme variable colors, and the other two are located in component folders. When I import the main SCSS file into the ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

Having trouble with CSS3 radio buttons not functioning properly on Firefox?

Does anyone know why my CSS3 pseudo elements are working fine in Chrome, but reverting back to default styling in Firefox for my radio button? Any suggestions? Check out this JSFIDDLE link for reference: JSFIDDLE Here is the HTML code snippet: <input ...

Arrange divs in a stack fashion

Currently, I have a table-styled three-column set of divs. I would like these columns to stack vertically on mobile devices. I think this can be achieved using the float method, but the titles and descriptions for each column are in separate rows (divs), ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...

Tips for including a decimal point in an angular reactive form control when the initial value is 1 or higher

I am trying to input a decimal number with 1 and one zero like 1.0 <input type="number" formControlName="global_velocity_weight" /> this.form = this.fb.group({ global_velocity_weight: new FormControl(1.0, { validators: [Valida ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

Having no capability to manipulate CSS using jquery

In one of my divs, the CSS is set to have display: none .cookie_policy { color: white; text-align: justify; width: 50%; margin: 2% 25%; line-height: 20px; display: block; font-family: Arial,Helvetica,sans-serif; font-style: italic; display:none; } <div ...

Shade of a row within a PHP table

I have a table that is populated with data from a database. Is there a way for me to dynamically change the color of a row based on certain conditions from a JSON file? For example, if the temperature exceeds a set minimum value, I want to highlight the ro ...

Attempting to upload a file into the system

I'm in the process of creating a website that allows for file uploading. Check out my code below: index.php: <?php include('/inc/header.php'); ?> <?php if($_SESSION['username'] != null) { echo " <form class=&bs ...

Is there a way to determine whether my CSS style modifications will impact other web pages?

Managing a team of junior developers has its challenges, especially when they unknowingly make CSS style changes that impact multiple pages on our website. Is there a tool or method available to alert them that modifying the color of a specific class will ...

navigating up and down html elements using css selectors

Within my code, I have this odd repetitive HTML structure (with no classes) and I'm looking to extract all links along with the accompanying text below each link. While it's simple enough to grab all the links using a basic CSS query selector li ...

Increase or decrease the quantity of items by cloning with Jquery and dynamically changing the ID

Currently, I am working on a jQuery clone project where I need to dynamically add and delete rows. Despite searching extensively on Stack Overflow and Google, I only have a basic understanding of how jQuery clone works. Any suggestions would be greatly ap ...

The functionality of Selenium's get(link) feature appears to be experiencing issues

Recently, I wrote a simple piece of code using selenium to open a webpage. from time import sleep from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import warnings warnings.simp ...

"Exploring the Dynamic Duo of AngularJS ngAnimate and animate.css

I've been working on getting my animation to function correctly with AngularJS and animate.css. In order to achieve this, I set up the SASS in the following way: .slide-animate { &.ng-enter, &.ng-leave{ } &.ng-enter { ...

Manipulate container (div) to reveal and conceal

My jQuery was working fine until I added some more divs to my HTML. I'm now trying to toggle the opening and closing of a discussion container named discussionContainer with a click on the button replyButton. Any assistance would be highly appreciated ...

The Canvas element inside a Bootstrap modal is returning inaccurate mouse coordinates

I am currently troubleshooting an issue with a HTML5 canvas inside a Bootstrap modal. The canvas is designed to be a selection game where objects can be selected and manipulated. Everything works fine in the center of the 600x600px canvas, but there is an ...

Concealing specific HTML elements with ng-view in AngularJS

I recently started a project in AngularJS and I'm utilizing ng-view with $routeProvider for templating. However, I've encountered a minor issue where I don't want the navbar to display on specific pages like the landing, login, and registrat ...

Centered Layout using HTML and CSS

Exploring the world of Ruby on Rails and HTML has been quite an adventure. Today's question veers away from RoR and focuses on HTML and CSS. As I attempt to center my body, a peculiar issue arises: Help me solve this problem here How can I align the ...

Encountering a Blank Area at the Top of a Printed AngularJS Screen

Currently, I am tackling an issue in AngularJS while working on the Print Invoice Page. The problem I am encountering is a blank space at the top of the printed screen. Check out the image here Below is my code: HTML <div id="invoice" class="compact ...