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 CSS Selectors Selectors - Beyond the Basics Attribute Selectors Challenge

Nayoon kim
Nayoon kim
3,098 Points

I get { margin: auto } to position it in the middle . but what is the difference btw ....

{ margin: 10px auto; } and {margin: 0 auto} ; ? is it just that the first one has 10px top and bottom margin ? and the latter shows a box that is fixed to the top ?

I think I read about something like,,, if it is {margin: 0 auto}, it will be in the centre even if I shrink the browser down. but like, what about { margin: 10px auto; } ? doesn't it do the same thing, positioning it in the centre?

2 Answers

Hi Nahoon,

When applying two values for margins at the same time. The first value means the vertical margin, and then the second value is the horizontal margin.

With the following code. You would be applying a 10px top and bottom margin, with an automatic horizontal margin.

.class { 
margin: 10px auto; 
}

With the following code. You would be applying no top and bottom margin, with an automatic horizontal margin.

.class { 
margin: 0 auto; 
}

So in the end, no they aren't the same. Horizontally, the margins are the same. Vertically, they are different.

For further information review this:

Examples:

margin:10px 5px 15px 20px;
    top margin is 10px
    right margin is 5px
    bottom margin is 15px
    left margin is 20px

margin:10px 5px 15px;
    top margin is 10px
    right and left margins are 5px
    bottom margin is 15px

margin:10px 5px;
    top and bottom margins are 10px
    right and left margins are 5px

margin:10px;
    all four margins are 10px
Nayoon kim
Nayoon kim
3,098 Points

ah, I see it. I just wanted to know why they would use margin: 10px auto ; instead of margin: 0 auto ; if they just wanted to position the element centre. Thanks for the help !

Jack Cummins
Jack Cummins
17,417 Points

{ margin: 10px auto; } will also center the element, but {margin: 0 auto;} is best practice.

If you liked my answer you can upvote it and give it a best answer.

Your Welcome, Jack