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 trialCasey Rochester
3,626 PointsHow do I use the margin property to center in CSS?
I can't figure out the correct code for the margin property.
3 Answers
Austin Whipple
29,725 PointsThe basic code to center an element with margins is margin: 0 auto;
This will set the top and bottom margins to zero (though you can add margins there if you'd like) and let the browser equally distribute the space not taken up by the element on either side.
All that said, you'll need to make sure the element you're positioning here has a defined width, so if it is a block level element, provide a width in pixels or percentages before applying the margins.
More information can be found on CSS-Tricks.
James Preus Jr.
Courses Plus Student 8,582 PointsThe following is how you would center an element using CSS margins.
.className {
width: 960px;
margin: x auto;
}
First you have to set the width of the element. Then you set the margin to "x auto" like I have above, where x is the value you would like to set for the margin top and bottom. That's all there is to it.
Casey Rochester
3,626 PointsThanks so much!