Centering Navigation Items in Bootstrap
In Bootstrap 4, aligning the navigation items (links) horizontally can be achieved using flexbox and margin utilities.
Bootstrap 4 Alpha 6 and Later
To center both brand and links in Bootstrap 4 alpha 6 and onwards:
<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" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="d-md-flex d-block flex-row mx-md-auto mx-0"> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse mr-auto">
In this code, the d-md-flex and d-block classes are used to align the brand and links horizontally in medium-sized screens and above. The flex-row class ensures the items are arranged side-by-side. The mx-md-auto and mx-0 classes center the items in the available space, adjusting for the width of the brand image.
Bootstrap 4.1
For Bootstrap 4.1:
<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" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse">
In this case, mx-auto is applied directly to the navbar-nav to center the links only. The brand can be centered using other techniques such as justify-content-center.
Positioning Links Exactly in Viewport
To center the links exactly in the viewport, consider this technique:
<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" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-nav">
Here, the navbar-nav is given a fixed width and justify-content: center to align the links precisely in the center of the screen.
For further customization and additional examples, refer to the links provided in the reference section below.
The above is the detailed content of How can I center navigation items in Bootstrap 4?. For more information, please follow other related articles on the PHP Chinese website!