Home > Web Front-end > CSS Tutorial > How to Center Navigation Items in a Bootstrap 4 Navbar?

How to Center Navigation Items in a Bootstrap 4 Navbar?

Barbara Streisand
Release: 2024-12-06 20:47:13
Original
266 people have browsed it

How to Center Navigation Items in a Bootstrap 4 Navbar?

Centering Navigation Items in Bootstrap

In Bootstrap 4, aligning navigation items (links) to the center of the navbar can be achieved by utilizing flexbox properties. Here's how:

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup">...</button>
    <a class="navbar-brand" href="#">...</a>
    <div class="collapse navbar-collapse mr-auto">
Copy after login
Copy after login

CSS:

.navbar {
    display: flex;
    justify-content: center;
}
Copy after login

The above code uses flexbox's display property to set the navbar to a flex container, and justify-content to align the navigation items to the center. Bootstrap's collapse class is used to hide the navigation items on smaller screen sizes.

Responsive Adjustment

For responsiveness, you can use Bootstrap's mr-auto utility class to ensure the navigation items center correctly as the browser size changes:

<div class="collapse navbar-collapse mr-auto">
Copy after login

Example

Consider the following code:

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup">...</button>
    <a class="navbar-brand" href="#">...</a>
    <div class="collapse navbar-collapse mr-auto">
Copy after login
Copy after login

CSS:

@media (min-width: 768px) {
    .navbar-nav {
        justify-content: center;
    }
}
Copy after login

This code adds a media query that sets the justify-content accordingly when the browser window width is greater than 768px, centering the navigation items only on larger screens.

The above is the detailed content of How to Center Navigation Items in a Bootstrap 4 Navbar?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template