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).

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

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:

https://i.sstatic.net/IGYng.png

https://i.sstatic.net/gMlCH.png



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

Determine how to use both the "if" and "else if" statements in

/html code/ There are 4 textboxes on this page for entering minimum and maximum budget and area values. The condition set is that the maximum value should be greater than the minimum value for both budget and area. This condition is checked when the form i ...

Using a subheader in conjunction with a virtual repeater in markdown does not function correctly

Currently, I am utilizing angular 1 along with angular material. I am trying to incorporate md-subheader with multiple md-virtual-repeat-containers within an ng-repeat loop. The source code can be found on this codepen. The issue I am facing is slightly c ...

Incorporating headers and footers on every page

I am looking to incorporate a header and footer on all my pages. I attempted to do this using jQuery, but unfortunately, it was unsuccessful. Since I am using nodeJS on the backend, do you have any recommendations for implementing this without causing an ...

Challenges with arranging tables properly in React using Material UI

I am struggling to make this inner table span the full width and merge with all 8 columns. I have been unable to get the colspan attribute to work with material UI. The inner table is collapsible, which is working correctly, but the formatting of the table ...

Overflow scrollbars do not appear on flex divs

I am struggling with implementing a simple flex container that contains standard divs. The issue I am facing is that the overflow does not display a vertical scroller as desired. In order to achieve this, I have included the following CSS code snippet: #c ...

Tips for applying styles to elements that are not directly related when the parent element has a specific class using CSS

I have some HTML code structured as shown below. <div class='A'> <div class='B' /> <div class='C' /> </div class='A'> <div class='D' /> My Objective: If A contains C: ...

Managing and keeping track of a universal value within the success callback function among numerous Ajax POST requests

I am faced with a challenge involving two HTML elements: 1). a div element that functions as a multiple select, created automatically by a predefined widget, and 2). a button that triggers an onclick event. On the JavaScript side, I have a global variable ...

"Troubleshooting a dropdown navigation bar problem in CSS

I am currently working on creating a CSS navbar dropdown, but I am encountering some issues. I am not very experienced with CSS, so any assistance would be greatly appreciated. The text within the "Products" box is not changing color like it should, and yo ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Executing PHP queries with the help of jQuery

Currently, I am developing a webpage that involves checking a checkbox to trigger a PHP function which queries the table for user existence. If the user exists, a button is displayed allowing them to proceed to the next page. I have made an attempt at thi ...

Using JavaScript to convert the text within a div into negative HTML code

I am working with this specific div: <div class="signs" id="signs" onclick="toggle()">&#43;</div> It currently displays the positive sign. I have set up a JavaScript function that is triggered when the div is ...

Guide to automating the versioning of static assets (css, js, images) in a Java-based web application

To optimize the efficiency of browser cache usage for static files, I am seeking a way to always utilize cached content unless there has been a change in the file, in which case fetching the new content is necessary. My goal is to append an md5 hash of th ...

Is my Bootstrap malfunctioning? The grid system seems to be malfunctioning

My very first question here is quite simple. I have a script that creates rows with dynamic content by appending 4 boxes (columns) in one row and then appending the row to the container. After completing this process, it appends the container to the main c ...

Utilizing columns within the 'segment' element in Semantic-ui to enhance layout design

I am looking to divide the ui-segment into 3 columns and display the ui-statistics evenly. Below is the code I have used in an attempt to achieve this: <div class="ui container"> <div class="ui segment"> <h3 class="ui header"> ...

Refreshing a page using AJAX form functionalities

After spending some time searching, I am unable to find a satisfactory solution to my issue. I have a "finance" tracker that includes hidden divs which are displayed using jQuery when the corresponding button is clicked. Additionally, I have an Asset Track ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...

Guide on validating multiple preselected checkboxes using Angular 8 reactive forms

I have a problem with validating checkboxes in my Angular application. The checkboxes are generated dynamically from an array using ngFor loop, and I want to make sure that at least one checkbox is selected before the form can be submitted. The validatio ...

Is there a way to automatically scroll vertically to a specific line in HTML?

Trying to explain this is a bit tricky. I am looking to add an element to the HTML that prompts the browser to scroll vertically to its location automatically when loaded, similar to an anchor. So: | visible area | | content html | | content html | ...

I am unable to see the text field when I use element.text. What could be the reason for this

As I work on collecting online reviews using Selenium Chrome Webdriver, I've encountered a challenge with TripAdvisor. The reviews are truncated and require clicking a "More" button to view the complete text. Within the html code, there is a class cal ...