How to center div
Centering a div is a common task in web development. Below are several methods to achieve this,
including a Bootstrap example.
Using Bootstrap's Flexbox Utilities
The outer div uses d-flex, justify-content-center, and
align-items-center to center its content.
This div is horizontally and vertically centered using Bootstrap.
<div class="d-flex justify-content-center align-items-center" style="height: 20vh;">
<div class="bg-primary text-white p-3">
<p>This div is horizontally and vertically centered using Bootstrap.</p>
</div>
</div>
Using CSS Margin Auto
The margin: auto; property centers the div by adjusting its left and right margins.
Setting width to 50% makes the centering more visible.
This div is horizontally centered using CSS margin auto.
<div style="width: 50%; margin: auto;" class="bg-primary text-white p-3">
<p>This div is horizontally centered using CSS margin auto.</p>
</div>
Using Grid Layout
The display: grid; and place-items: center; properties center the div
horizontally and vertically.
This div is both horizontally and vertically centered.
<div style="display: grid; place-items: center; height: 20vh;">
<div class="bg-primary text-white p-3">
<p>This div is both horizontally and vertically centered.</p>
</div>
</div>