Bootstrap Utilities
Center a box horizontally and vertically with flex utilities
Description: A parent has a height of 200px. Put a blue box in the exact center, horizontally and vertically.
Hint:
- Use
d-flex,justify-content-centerandalign-items-centeron the parent.
Solution
<div class="d-flex justify-content-center align-items-center bg-body-secondary" style="height: 200px">
<div class="p-3 bg-primary text-white rounded">I am in the center</div>
</div>
Live preview
How it works
justify-content-centercenters on the main axis (horizontal).align-items-centercenters on the other axis (vertical).- The parent needs a height, or there is no free space to center in.
Read Flex Utilities.