How to use mx-auto class in a Flex In Bootstrap
In this approach, we are using Flex container (d-flex) and using alignment and justification utilities (align-items-center, justify-content-center) along with the mx-auto class on the target div (custom-container) to create the div element. This makes sure that the container is centered horizontally and vertically.
Syntax
<body class="d-flex align-items-center justify-content-center vh-100">
<div class="mx-auto custom-container p-4 text-center">
<!-- Content -->
</div>
</body>
Example: Below is the implementation of the above-discussed approach.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < link href = "https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel = "stylesheet" > < title > Center Div with mx-auto in Flex </ title > </ head > < body class= "d-flex align-items-center justify-content-center vh-100 bg-light"> < div class = "mx-auto p-4 text-center bg-white shadow-sm" > < h1 class = "text-success" >w3wiki</ h1 > < h3 class = "mb-3" > Approach 2: Using mx-auto class in a Flex </ h3 > < p class = "text-muted" > Explore our vast collection of programming courses and articles at w3wiki. </ p > class = "btn btn-success" > Visit w3wiki </ a > </ div > < script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" > </ script > </ body > </ html > |
Output:
How to Center a Div with the mx-auto Class in Bootstrap 5 ?
In this article, we will discuss two different methods to center a div using the mx-auto class in Bootstrap 5. These methods provide practical solutions for both container and flex layouts. The first approach uses the Bootstrap grid system to center a card within a container. The second approach uses flexbox utilities to demonstrate horizontal and vertical centering for a responsive layout.
Table of Content
- Using mx-auto class in a Container
- Using mx-auto class in a Flex