What does auto do in margin: 0 auto?
Solution 1:
When you have specified a width
on the object that you have applied margin: 0 auto
to, the object will sit centrally within it's parent container.
Specifying auto
as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.
margin-top: 0;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto
property will determine that there's 50px of free space to share between margin-left
and margin-right
:
var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;
Which would give:
margin-left: 25;
margin-right: 25;
Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.
Solution 2:
auto: The browser sets the margin. The result of this is dependant of the browser
margin:0 auto specifies
* top and bottom margins are 0
* right and left margins are auto
Solution 3:
From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
Solution 4:
margin:0 auto;
0
is for top-bottom and auto
for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container.
Generally if you want to put any element at center position then margin:auto
works perfectly. But it only works in block elements.