Write CSS to centre a div horizontally and vertically using Flexbox

Description: Centre a small box in the middle of a 200px high container.

Hint:

  • Make the parent a flex container.
  • Use justify-content: center and align-items: center.

CSS to centre a div with Flexbox

<style>
  .parent {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
    background: #eceff1;
  }
  .child {
    padding: 12px 20px;
    background: #7e57c2;
    color: white;
  }
</style>

<div class="parent">
  <div class="child">Centred</div>
</div>

Output in the browser:

Output in the browser
Centred

How it works

  • justify-content works on the main axis (horizontal by default) and align-items on the cross axis (vertical).
  • The parent needs a height, otherwise there is no free space to centre in.

Read CSS Flexbox.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.