Posts Tagged ‘box model’

Understanding Margin and Padding

Understanding Margin and Padding

written by: jason 1 Comment

Before I started designing for the web, I read a lot of blogs and tutorials on box modeling. Box modeling is basically the html way of laying out your design in a series of “divisions”, referred to as divs, or any other block-level elements (ex. h1-h6, paragraphs, block-quotes, unordered lists, ordered lists, etc.) and then controlling their precise location using your stylesheet (css). One way of fine tuning these elements is with margins and padding. This illustration shows the relationship between margin and padding to an element. In this case, a box:

margin and padding

Adding a Border

That was easy enough to comprehend. Now let’s dig a little deeper. What happens if you add a border? Let’s say you have a box with a width of 100px and margin left and right of 10px each. The total width is calculated by adding the width of the box (100px) + both right and left margins (10px+10px=20px). That would make a total width of 120px.

Now let’s add a 1px border around the entire box (graphic below). Guess what? You just increased the overall width of that box by 2px (1px on the left and 1px on the right).

margin with border

Same thing goes for padding. If you add padding back into the mix, you’ll have to remember to account for those values when determining your overall width (or height).

Where does this come into play?

The most common place to see this in action is in a sidebar. Here’s the scenario. You have a fixed width layout with you blog posts on the left and a sidebar on the right. You know your div wrapper is say 930px wide. Therefore, you calculate that you can have your blog posts be 600px wide and your sidebar 330px wide. So you go to your favorite browser load it up and lo and behold, your sidebar is floating down beneath your blog posts! WTF?! Nine out of ten times, you probably have either a stroke or margin on the left side of your sidebar or a stroke or margin on the right hand side of your main content which holds your blog posts. Subtract the total width of the stroke or margin from either the sidebar or content area and it should bounce right back up where it belongs. It’s an easy fix but can cause a major headache if you forget to account for that. 🙂