The CSS box model: explaining borders, margins and padding

CSS makes laying out content quite simple. However, an understanding of the “box model”, used to position objects in the page, is essential (read to the end because the thing that’ll catch you out every time is there). I’ve coloured the elements in this diagram to show them:
Diagram of padding, borders and margins in the CSS box model
Note that the contents and padding will have the background color or image which is assigned to the content. The margin does not.

Here’s an example:


DIV.quote {
padding: 16px;
border: 1px solid black;
margin: 12px;
}

Each of these 3 can be specified separately for the top, right, bottom and left sides.
Here’s an example of setting them individually:


IMG.pictureonleft {
padding-right: 16px;
padding-bottom: 12px;
}

And setting them all in one go (the order is clockwise from the top – top, right, bottom, left):


IMG.pictureonleft {
padding: 0px 16px 12px 0px;
}

There’s an important gotcha here. If you specify the width or height or an element in the page then the margin, border and padding are all added. So in other words, if I have:


DIV.redbox {
width: 200px;
padding: 16px;
border: 1px solid black;
margin: 12px;
}

Then that’ll be 200 + 2*16 + 2*1 + 2*12 = 258 pixels wide. Er, obviously?!!?

Share this:
Share this page via Email Share this page via Stumble Upon Share this page via Digg this Share this page via Facebook Share this page via Twitter

Leave a Comment