Horizontally center elements on a page using margin
suggest changeAs long as the element is a block box in normal flow and its width is not auto, margin-left and margin-right set to auto center it horizontally within its containing block.
Set a width smaller than the containing block. auto margins then split the leftover space between the left and the right:
#myDiv {
width:80%;
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, #myDiv is 80% of the containing block’s width, which leaves 20% leftover. The browser splits that leftover between the two auto margins:
(100% - 80%) / 2 = 10%
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents