Write CSS to centre a box horizontally using margin auto

Description: Centre a box of width 250px horizontally on the page.

Hint:

  • A block element with a width can be centred with margin: 0 auto.

CSS to centre a box with margin auto

<style>
  .box {
    width: 250px;
    margin: 0 auto;
    padding: 16px;
    background: #ffe0b2;
    text-align: center;
  }
</style>

<div class="box">I am in the centre.</div>

Output in the browser:

Output in the browser
I am in the centre.

How it works

  • margin: 0 auto means zero margin on top and bottom, and automatic margin on left and right.
  • The browser splits the free space equally on both sides. Without a width, the block takes the full width, so there is no free space to share.

Read CSS Margins.


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