CSS box model
January 24th, 2006 by Sonja DuijvesteijnIn CSS a lot is based around the box model, but what is that, and how does it work?
A box or a block?
In the css specs of the W3C they mention the box model, which also applies to block elements. However, they also apply to for example tables, and even to the body element. An element has a set display mode which has it’s own restrictions to it. However with css you can change these settings. W3schools has a good overview of the different settings.

This could be any typical div block. A block has a number of properties an inline element (like span) doesn’t have. Important ones are the padding and the margin. The difference between those can be quite unclear when you start with css.
When you set the background-color for a block however this will become clear. A margin is outside the actual block, and a padding is on the inside. So, a background color will be show in the padding, but not in margin. The margin is always transparent. The actual content for a box will only show after the space for the padding.
Width of a block
An important thing to remember when you set the width of a block type element (such as div) is that that width applies to the content only. So any padding and borders you add will be counted as well. This can be confusing when you just start with blocks.
Positioning the content
The content of a block can be positioned where you want it.
div {
text-align : center;
vertical-align: middle;
overflow: hidden;
}
With this code the text in every div will be aligned in the middle of the block, both vertically and horizontally, and everything that doesn’t fit will be hidden.
Position the block
Besides being able to place the content in the block at the right place you can also place the block at the right location. You can set the distance from the top, the left, the right and the bottom of the parent element. This parent element can be another block, a table or the body element. More important is the position: relative and position: absolute. That way you can set where the container the block is shown.
<div>
Some text to make do some filling up.
<div class='footer'>
The footer information
</div>
</div>
In this case the div with the class ‘footer’ would be shown on the line after the text. However, as it’s a footer you might want it to show up on the bottom instead. So, add a bit of css
div.footer {
position: absolute;
bottom: 12px;
}
With this CSS the block will be placed at the bottom of the parent element. However you might not want this. You could want this to be placed 12px below the previous text.
div.footer {
position: relative;
top: 12px;
}
That’s the basis of the box model, the best way to get a real feeling for it however is to get some hands on experience and try it out. Good luck.
Related posts
No related posts.