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
Fedor Andreev
6,438 PointsI never understood this margin code? Help?
margin: 0 auto;
I understand what a margin is, I understand what auto means and 0. But what the hell does 0 and auto together mean? So no margin and automatic margin? Why not just put auto, adding 0 means nothing???
4 Answers
Ricardo Hill-Henry
38,443 PointsJoe and Kukasz are pretty much right. The top, and bottom margins (o in this case) don't have to be necessarily 0. You usually see it as 0 because this is typically used for a main wrapper of some sorts.
More importantly the auto keyword tells the browser to calculate the available space left in the viewport and distribute (by dividing by 2 I assume) it evenly to both the left and right sides (margins).
So if I had a wrapper with 800px, and the users viewport size was 1000px at the moment; the browser would do something like this:
viewport - container: 1000px - 600px = 400px
400px / 2 (margin-left and margin-right) = 200px
So in this case both left and right margins will equal to 200px. As the viewport resizes, the margins resize accordingly.
Joe Mills
18,617 PointsI believe when there are 2 values the first is for the top and bottom, the second is left and right. In your example the top and bottom would have 0 margin and auto would center the element in the page (equal amount left and right)
Luke Buśk
21,598 PointsJust as Joe Mills said, margin 0 auto is a shorter version of margin top 0, margin bottom 0, margin left auto and margin right auto. Margin 0 sets top and bottom margins to 0 and auto sets horizontal margins evenly on both sides depending on the set width of the body/document that You did set up.
If You for example set 600 width body, then margin auto will position this block evenly from left and right side, thus centering it.
Adam Duffield
30,494 PointsI think the zero overrides any browser based setting by resetting it to zero and auto just centers the block.