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
Barbara StreisandOriginal
2024-12-06 20:47:13264browse

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">

CSS:

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

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">

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">

CSS:

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

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!

Statement:
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