Thinking inside the box model

A step by step look at margin, padding and border

3/27/2015

The CSS box model is an essential concept to wrap your head around when styling an HTML page.

margin, padding and border all work together to push your elements around and frustrate you to no end.

Above we see four div tags in their natural state. There is a background-color applied to make them stand out from each other. But there is no margin, no padding and no border. They naturally fill up the full width of their container.

Here I have added 50 pixels of margin to each div. Take note that the elements are moving away from the left and ride sides as well as the top and bottom.

Now I have set the margin back to 0 and added 50 pixels of padding.

Padding is like blowing up a balloon and margin is like moving the balloons further apart.

Here's what adding 25 pixels of margin and 25 pixels of padding looks like. There's a certain balance here that pleases my eye.

Something interesting happens when I add in display: inline-block to our elements. We still have 25 pixels of margin and 25 pixels of padding But the elements are no longer taking up the full width of the page, they are only as big as the content inside them. This makes for some nice symmetry.

But this is where things start getting messy for us. If I add more content to the first div, our symmetry goes out the window.

One way to get our blocks looking symmetrical again would be to give them all a fixed width. Here I gave each div a width of 50 pixels. Practice makes perfect. As you play with different properties you will see what lines up best.

If you're trying to get your elements to line up picture perfect, watch out for the border property. As the example above shows, a border will add extra padding to the outside of your element. This is 3px solid blue border is a probably more flamboyant than what you'll use, but it shows how off center a border will get you.

Move stuff around, try different sizes and keep playing with your CSS. You'll find a happy medium inside the box model.