Struggling to align navigation items in the center while maintaining responsiveness with CSS and Bootstrap

I am trying to achieve a responsive centering of my navbar-brand across all platforms, while also positioning my nav items and links, including the navbar-toggler, on the right side. Currently, on larger screens, it appears as shown in this image: here. However, I am struggling to get the navbar-brand centered at all.

When I shrink the screen below 991px, the navbar does center, but the alignment with the items looks strange. You can see how it appears on smaller screens here.

I am only using Bootstrap and my CSS file is empty so far. I have attempted to override the styling in my CSS file, but it does not center the navbar. I have also consulted Bootstrap's documentation, but I have been unable to resolve the issue.

I suspect the problem lies with the navbar-expand-lg class, as it impacts the alignment of the nav-links and navbar-brand when the screen shrinks below 991px. Here is the code I am using:

<div class="collapse navbar-collapse" id="navbarTogglerDemo01">
                <ul class="navbar-nav ms-auto ">
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 1</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 2</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 3</a>
                    </li>
                </ul>
                </div>
            </div>
            </nav>

Answer №1

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b5954544f484f495a4b6b6eb16c717c627f337e626a63">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark position-sticky">
        <div class="container-fluid text-center">
            <a class="navbar-brand mx-auto" href="#">brand</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01"
                aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse me-5" id="navbarTogglerDemo01">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 1</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 2</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 3</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="097b76767d7a7d7b7879496e616c717f636e227f636b6272">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
        crossorigin="anonymous"></script>
</body>

</html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14767b7b60676066756454213a273a24397578647c7525">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark position-sticky">
        <div class="container-fluid text-center">
            <a class="navbar-brand mx-auto" href="#">brand</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01"
                aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse d-flex justify-content-center" id="navbarTogglerDemo01">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 1</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 2</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link 3</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64060b0b10171016051424514a574a54490508140c0555">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
        crossorigin="anonymous"></script>
</body>

</html>

Answer №2

There is a layout issue where the .navbar-brand does not align properly with the .nav-links due to the space occupied by the .navbar-toggler. To resolve this, Bootstrap's position utility classes can be utilized. By applying .position-relative to the .container-fluid and .position-absolute.top-0.end-0 to the .navbar-toggler, the toggler can be positioned at the top right corner while keeping everything else centered within the container width.

When an element is relatively positioned, it remains in the normal flow of the document. On the other hand, absolutely positioned elements are taken out of the flow, affecting the positioning of other elements as if it did not exist. The absolutely positioned element is relative to its nearest positioned ancestor, or the ICB (initial containing block) if no positioned ancestor exists.

--source: MDN

To achieve a centered layout on two lines in expanded view, adding .flex-wrap to the container and .w-100 to the brand can help. This setup allows the brand to span the full width with centered text, while the .navbar-collapse wraps to the next line with centered contents using .justify-content-center.

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 maintain the formatting of a textarea in the database?

My HTML form includes a text area and a functionality to save the data into a database upon submission. The issue arises when the saved data is retrieved from the database, as the original formatting of the text gets altered. For instance: "This is a text ...

Transferring information to the specified link using AJAX and PHP

I'm having trouble sending data to a link that I click on. Whenever I try, I just end up with an undefined index error in my PHP file. <a href="output.php"> Click me </a> ('a').click(function(){ href = "output.php"; ...

css position:absolute stacked

Looking for a solution, I'm trying to include a side menu (navbar) on my page by using position: fixed. However, I am facing an issue where all the HTML elements I attempt to add are ignoring it. Check out the positioning problem here. ...

Update the React component without needing to reload the entire webpage

Every time I attempt to render a new component, the entire page refreshes instead of just the components re-rendering. Upon loading the page, when I click the drop down menu in the header, it successfully renders a new component without any refreshing. Ho ...

Unable to get 100% height to work properly in HTML5 ASP.net because of the DOCTYPE

I'm currently working on creating an Asp.net website with a unique single-page portfolio style for the homepage. Each project or section should be 100% height of the viewport, stacked underneath each other to make use of anchor tags. However, I'm ...

The parcel project's file size is massive

Greetings! As a graphic designer venturing into the world of coding, I find myself facing an interesting dilemma. My current project involves using Parcel 2 with Bootstrap 5.3 and includes a sizable video file of around 8 GB. However, the total file size o ...

Ways to modify the background color of the entire body excluding a sidebar div

How do I implement an overlay and dim the screen after clicking on a menu button? <ul id="gn-menu" class="gn-menu-main"> <li class="gn-trigger"> <a class="gn-icon gn-icon-menu"><span>Menu</spa ...

What are the best methods for aligning pseudo elements vertically?

I am facing an issue with the placement of a before and after pseudo element for articleSubTitle. The problem occurs when the text from articleSubTitle wraps to a new line within a small container or on mobile devices. This causes the after element to appe ...

Tips for Editing an HTML File

As a beginner in the world of coding, I am currently working on creating a quiz maker. My question is how can I use code to edit a file? For example, if a user inputs a question name, how can the code automatically update the corresponding question in th ...

Utilize the power of jQuery for form validation by combining the errorPlacement and showErrors functions

I am currently attempting to implement validation using the Jquery .validate plugin. Unfortunately, I have encountered an issue where I am unable to utilize both the errorPlacement and showErrors methods simultaneously. If you'd like to see a demons ...

Looping through Vue with multiple options

Looking for help with Vue2 looping to display multiple options within a select element. We have an object structured like this; sorting = { name: [ 'asc', 'desc' ], price: [ 'cheapest', ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

Place your cursor over the following element to take control

There is a paragraph that needs to be clipped when hovered over. An issue arises where the H1 text shifts its position. Only the phrase "HOVER ABOVE PARAGRAPH" should be concealed. * { margin: 0; box-sizing: border-box; } .wrapper { displ ...

Extract data from a JSON object and connect it to input fields on a form

I am currently working with a large JSON object that I need to parse and bind to various form fields. Here is a snippet of the code, but you can view the entire code here. The main question I have is what would be the most efficient way to achieve this? Wo ...

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

ChakraUI failing to display on the screen

Exploring Chakra UI in my latest project has been an exciting journey for me. I made sure to install all the necessary dependencies and started importing components from the ChakraUI Docs. Initially, I successfully imported and rendered the button feature ...

Switch button displaying stored data in sessionStorage

I am facing an issue with my small toggle button in AngularJS. I have set up sessionStorage to store a value (true or false), and upon page load, I retrieve this value from sessionStorage to display the toggle button accordingly. Depending on the value sto ...

Tips for modifiying date format in React app

I'm encountering an issue where I can't modify the date format, preventing me from displaying the date on the frontend. Currently, I'm utilizing the dateformat package. import dateFormat from "dateformat"; const EditFinancialInfo ...

Shape with smoothed corners

Is there a way to create rectangles with rounded corners using CSS, SVG, or other methods while maintaining straight horizontal and vertical sides? I attempted to use border-radius for the rounded corners, but found that it created curved edges on both ho ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...