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-center and align-items-center on 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-center centers on the main axis (horizontal). align-items-center centers on the other axis (vertical).
  • The parent needs a height, or there is no free space to center in.

Read Flex Utilities.


Learn more about the similar topics:
Tutorials
Bootstrap Spacing: Margin, Padding and Gap
Bootstrap Flex Utilities
Bootstrap Utilities
Exercises & Assignments
Center a box horizontally and vertically with flex utilities
Interview Questions & Answers
How do you center content in Bootstrap?
What are the spacing classes (margin and padding) in Bootstrap?
How do you show or hide elements on different screen sizes in Bootstrap?
What is the difference between d-none, invisible and visually-hidden?