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
CSS Layout – The display Property
CSS Position Property
CSS z-index
CSS Float and Clear Property
Exercises & Assignments
Write CSS to centre a box horizontally using margin auto
Write CSS to create a horizontal navigation menu
Interview Questions & Answers
What is the use of float property in CSS?
What is the difference between display none and visibility hidden?
What is the difference between inline, block and inline-block?
What are the different values of the position property in CSS?
What is z-index in CSS?
What is clearfix in CSS?
How to hide an element in CSS?