To begin centering, we must understand the way values work on the margin, padding and border properties.
Selectors can have any number of declarations. Those declarations contain a property and a value. When we consider values for the properties of margin, border and padding, we can think of them as having four values: top, right, bottom, and left. With CSS we are able to adjust those values in four ways:
First, we can have a singular value such as margin: 20px. This will adjust all four sides of the margin 20 pixels.
Second, we can adjust the top and bottom AND the left and right at the same time like this: margin: 20px 30px;. This sets the margins on the top and bottom to 20px while also setting the left and right margins to 30px.
Third, we can adjust the top and bottom individually while adjusting the left and right at the same time with three values: margin: 25px 50px 75px;. This sets the margin on the top to 25px, the left AND right margins to 50px, and the bottom margin to 75px.
Lastly, we are able to adjust all four sides of the box model at the same time like this: margin: 0px 10px 20px 30px;. Picturing a clock, the arrangement works like this. Starting with the top the values work around the box clockwise. So with this example, we have a top margin of 0px, right margin of 10px, bottom margin of 20px and left margin of 30px.
Putting It All Together
Now that we understand how these values work with these properties, we can move on to putting this all together.
Consider our problem. We want to put ALL of our content in the center of the page. That should tell you we need to adjust the left and right of our box in some way. The top and bottom are fine; BUT in order to take advantage of the handy-dandy "auto" value, we need to go ahead and use the two value version we talked about above. In doing so, we will give the margins of the top and bottom a value of 0 while we give the right and left the value of "auto." It will look like this: margin: 0 auto;. What this is doing, is telling the browser to give the content of the selected element a top and bottom margin of 0 while also giving the right and left the SAME margin centering it on the page. Now, in order for this to work, we have to also give the element a width or max-width. Without giving it this value, how is the browser supposed to know how wide the element is supposed to be to center the content?
Perhaps the Hardest Part
For me, the most confusing thing about the box model is trying to figure out which html element I'm supposed to be selecting with CSS.
Remember me always talking about how html is like the branches of a tree and the CSS is the leaves or anything growing on those branches to make it look pretty? The hard part is figuring out which branch we need to pretty up. In MANY cases, we have to add a branch (an html element) to hang our leaves on.
How do we add branches? One way is to add a div, a class or both to your element and then make the content the child.