Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS How to Make a Website CSS: Cascading Style Sheets Style the Basic Elements

Pradeep Alabe
Pradeep Alabe
1,423 Points

Center alligning using margin

wrapper {

margin : 0 auto; }

center alligns the wrapper div , could you guys explain exactly what is happening here behind the scene

2 Answers

Margin is the distance between two elements.

Here shorthand method is used to provide margin property its value. The first value is for both top and bottom and the second value is for both left and right.

So here 0 px are assign for top and bottom margin and auto for left and right margin. As auto is assign processor will calculate margins by itself.

Ryno Botha
PLUS
Ryno Botha
Courses Plus Student 4,055 Points

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 = 100px - 50px;
var equalShare = freeSpace / 2;

Which would give:

margin-left: 25px;
margin-right: 25px;

Also look at:

http://learnlayout.com/margin-auto.html