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

The purpose of margin

could someone please explain to me why margin: 0 auto; centers the element in the page?

5 Answers

Although the wrapper appeared to be behind the image gallery think of the wrapper as actually surrounding the image gallery. Think of an element, like the wrapper, as a rectangle that can hold things inside of it. It's like having a piece of paper and gluing other things on top of the paper. It would defeat the purpose to glue things to the bottom of the paper where we cannot see it. When Nick specified the "background-color" property in CSS for the wrapper to be orange that is like using orange paper.

Next you might think, well the images were bigger than the orange part. Yes, they were. The wrapper is a container but just like any container, such as a jar, if you keep filling it with water eventually the water will spill over. It would be like trying to glue an 11 x 14 picture to an 5 x 7 piece of paper.

Hope that helps!

The margin is the space between the element and the other elements/page.

The first value, "0", sets the margin for the top and bottom of the element. The second value, "auto", sets the left margin and the right margin for the element. So, the space between the top and bottom of the element selected and the page is set to none and the space on the left and right of the element is automatically adjusted based on page width. Since both the left and right margins of the element are set to "auto" they will have equal widths. Hence, a horizontally centered element.

At least that's how I understood it...

Wait, is the wrapper the orange thing? if it is then some of this make sense however, I still have another question, why did the position of the image gallery? and why was the orange thing on the left of the image gallery? Thanks for answering my question.

Yes, in the video he gave the element the ID of "wrapper." (An ID is just like a name). The wrapper element was also the element that was centered.

He made "wrapper" orange temporarily to help us to see what he was actually chainging. Without doing this it would be very hard to visualize Nick's code. He returns the "wrapper" element to its original color in another video.

why was the orange wrapper behind the image gallery and not the other way around. And again thanks a lot for the help, I really appreciate it