Joe Levi:
a cross-discipline, multi-dimensional problem solver who thinks outside the box – but within reality™

CSS Box Model Tips and Tricks

CSS Box Model

Let’s face it, if you’re not familiar with the CSS Box Model, you’re probably not a web developer (or, if you are a Developer, you need some remedial education). The CSS Box Model is one of the most misunderstood patterns in CSS.

According to the World Wide Web Consortium (W3C):

The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model. The page box is a special kind of box that is described in detail in the section on paged media.

In plain language that means the CSS box model specifies the way a web developer should place a box on a web page.

“But that’s not hard to do, you just drop a DIV on the page and you’re done, right?”

That’s the way to get you started, sure, but there are some things you need to keep in mind, each block-element:

  • has an over-all width(measured differently in different web browsers, just to make your life more interesting).
  • can have a border on each side (optional)
  • can have padding (on each side) between the content and the border (optional)
  • can have margin (on each side) between the border and the element that it sits next to (optional)

imageThe following diagram from the W3C shows how these components relate to each other and the terminology used to refer to pieces of margin, border, and padding:

Here’s a tip for you that will save you countless hours of headache

When using DIV’s to layout a page (see diagram), don’t forget to use display:inline; to work-around MSIE’s annoying “double margin” issue. You can thank Anthony Short for this tip.

What you want: image What you get in MSIE: image

Another tip for content layout with floated DIVs

When you want two DIVs to sit next to each other (like above), under some circumstances you’ll end up with one of the two DIVs being forced below the other. To correct this, first make sure you’re using the display:inline; attribute (see above) to get rid of MSIE’s double-margin issue, the add overflow:hidden; to both DIVs. This will hide any content in the DIV that is too wide to fit and would mess with the layout. This is especially helpful if you’re pulling content in dynamically.

Don’t forget to break

After all is said and done, if you’re using floating DIVs for content layout if you want anything under the floated DIVs don’t forget to add clear:both; to that block-level element to tell it to fall under the floated DIVs.

You can thank me later. 🙂

Share

You may also like...

Leave a Reply