Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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