What is auto
do in margin:0 auto;
?
I cant seem to exactly understand what auto
does. I know it sometimes has an effect of centering objects. That's about it. Thanks.
What is auto
do in margin:0 auto;
?
I cant seem to exactly understand what auto
does. I know it sometimes has an effect of centering objects. That's about it. Thanks.
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 is does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first paramter 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;
Therefor, 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'll you do not have to specify the parent width, only the width of the child object.
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
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.