Aligning a Button in a Form
#1. If you're trying to center a button in a form, you can do it easily by placing a parent div
to the button with class text-center
.
<div class="text-center">
<button type="button" class="btn btn-primary px-3">Subscribe me to the Newsletter</button>
</div>
Works. But that's one extra DOM element (parent DIV to the button) to required.
#2. What if you want to place the button to the right of the form ?
One way is the add the classfloat-end
to the button.
<button type="button" class="btn btn-primary px-3 float-end">Subscribe me to the Newsletter</button>
<div class="clearfix"></div>
Works. But with this we need to add a clearfix. That's again, an extra DOM element. Moreover, less floats, the better.
#3. The default btn
class in bootstrap is of display: inline-block;
for which ms-auto (margin-left:auto
) and me-auto (margin-right:auto
) have no effect. So, if we change the display to block, then can use mx-auto and ms-auto.
<button type="button" class="btn btn-primary px-3 d-block ms-auto">Subscribe me to the Newsletter</button>
<div class="container mt-5">
<form>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Enter your email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com">
</div>
<div class="text-center">
<button type="button" class="btn btn-primary px-3">Subscribe me to the Newsletter</button>
</div>
<button type="button" class="btn btn-primary px-3 float-end">Subscribe me to the Newsletter</button>
<div class="clearfix"></div>
<button type="button" class="btn btn-primary px-3 d-block float-end ms-auto">Subscribe me to the Newsletter</button>
</form>
</div>