CSS Box Model

The CSS Box Model is essential when learning CSS to create web page layouts. Let’s take a look at the following diagram.

CSS Box Model

CSS Box Model

The CSS Box Model is a lot simpler than how it may look at first sight. Let’s begin with the content. Think of the content area an an empty div element. You add your content to it as you normally would.
<div class="my_div">Some content here</div>

.my_div{ }

Simple. Now let’s add some padding.
.my_div { padding:10px; }
Now the content in the div is pushed in 10 pixels in every direction (top, bottom, left and right), making it 20 pixels higher (top AND bottom) and 20 pixels wider (left AND right). This is represented in the above diagram.

Now we can add a border to the content.
.my_div {
  padding:10px;
  border:10px solid green;
}

This adds a 10 pixel green border all the way around the div element. Assuming that the original div is 100px high and 100px wide it is now:
100×100px + 20×20px (padding) + 20×20px (border). Remember that the border takes up 10 pixels on the left AND right, aswell as the top AND bottom, meaning 20px height and 20px wide.

And finally we have the margin. The margin doesn’t add any size to the div itself but instead spaces it out away from other elements. Imagine margin to be identical to padding but on the outside of the box. If we add 10 pixels of margin it will add 10 pixels to every side of the box, making the box 20 pixels wider, and 20 pixels higher.

So let’s summarise, a 100px box, with 10px padding, 10px border and 10px margin:
.my_div {
  padding:10px;
  border:10px solid green;
  margin:10px;
}

Will be 100px + 20px + 20px + 20px = 160px.

The CSS Box Model is a very important and simple theory to master before starting a

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • Live
  • MSN Reporter
  • MySpace
  • PDF
  • Ping.fm
  • Posterous
  • Reddit
  • RSS
  • Slashdot
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Tumblr
  • Twitter
  • Yahoo! Bookmarks
  • Yahoo! Buzz
This entry was posted on Saturday, January 16th, 2010 at 8:02 pm and is filed under CSS Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

1 Comment

  1. CSS Padding - CSS Tutorials and CSS Articles says:

    [...] CSS Padding January 16, 2010 – Posted by CSS Master CSS Padding is similar to CSS Margin and part of the CSS Box Model. [...]

    ... on July January 18th, 2010

Post a Comment