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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.