At first they may look confusing – especially for a beginner web designer, or for someone from the old school (tables!), but margins and paddings are actually a simple part of CSS, and something easily controllable if we just follow some basic steps.
A real life example
Photo by sandrino
One proven way of understanding how they work is by using a real life example: a box with something in it. If we take a box and fill it with Styrofoam, it will create a padding area: we have less space now to put an Apple TV inside. The styrofoam is the padding. The margin is added outside of the box – for example, if you don’t want any other boxes touching your precious Apple box, then you’ll use a margin, as it’s external to the box.
The box itself, the carton, is the border of our
divs. The material it is made of can be thinner or thicker, so can our CSS borders.
On the web
So how do browsers deal with these properties? Not consistently! First let’s take a look at how they should deal with it.
Although it would make sense to subtract the borders and paddings from the total of the box (
div), the W3C specifications are as follows:
The box width is given by the sum of the left and right margins, border, and padding, and the content width. The height is given by the sum of the top and bottom margins, border, and padding, and the content height.
So, if we have a
div with 100 pixels width + 20 pixels margin + 10 pixels padding, the total width of the space the
div occupies will be 160 pixels, for browsers that follow the specifications (try guessing which don’t).
Other browsers, like IE6 in quirks mode, will keep the original 100 pixels and reduce the available space inside the
How to deal with inconsistencies
The best way to deal with these inconsistencies is to follow 2 golden rules of CSS:
- If something has a padding, don’t give it a width
- If something has a width, don’t add any padding
So the best way to have a container with some padding, is to add the padding either to a second box inside it, or to the elements inside it (like paragraphs, headings or images). Or you can have an element that has no set width (like an
h2 heading) and just add some padding to it without risk.
Although this is a very simple introduction to how the box model works, it’s fundamental to understand when creating CSS layouts. If you’d like to know more about the subject, why not visit the resources links which have a lot more info on the subject?
- Box model
- Internet Explorer box model bug
- Box model tweaking
- Internet Explorer and the CSS box model
- The IE box model and Doctype modes
- The CSS Box Model