Horizontally center elements on a page using margin

suggest change

As long as the element is a block, and it has an explicitly set width value, margins can be used to center block elements on a page horizontally.

We add a width value that is lower than the width of the window and the auto property of margin then distributes the remaining space to the left and the right:

#myDiv {
 margin:0 auto;

In the example above we use the shorthand margin declaration to first set 0 to the top and bottom margin values (although this could be any value) and then we use auto to let the browser allocate the space automatically to the left and right margin values.

In the example above, the #myDiv element is set to 80% width which leaves use 20% leftover. The browser distributes this value to the remaining sides so:

(100% - 80%) / 2 = 10%

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents