PUBLISHED ON: AUGUST 7, 2021
How do I center align a button using Bootstrap 5?
The Bootstrap 5 Buttons can be combined with various components in the webpage. By default, the Bootstrap buttons are aligned to the left of the containing block but we can align it to the right or center by using some useful classes or CSS. Here we will learn to center align a button.
Creating a button using Bootstrap 5
The buttons can be created by using the <button> tag and .btn class in the bootstrap. See the example below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script></head>
<body>
<div class="container border border-primary">
<h2> Default alignment </h2>
<p> By default the button is aligned to the left side.</p>
<button class="btn btn-primary " >
Button
</button>
</body>
</html>
Output:
So here we can see that the button is left aligned to the container class.
Center aligning the buttons in bootstrap
The buttons can be aligned to the center using the text utility class. Just wrap the button to .text-center class. Here is an example to center align buttons using the text utility class.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script></head>
<body>
<div class="container border border-primary">
<h2> Default alignment </h2>
<p> By default the button is aligned to the left side.</p>
<div class="text-center">
<button class="btn btn-primary text " >
Button
</button>
</div>
</body>
</html>
Output:
See the button has been aligned to the center of the container.