Why does a CSS box model need a hack?

The CSS 1 specification by W3C that was released in 1996 stated that the width and height of a block level element should determine the visible content area. Any padding, margins and borders that are applied to it at any time are then added to the box width and height. This meant that any padding, border or margin added to the block level element would be calculated would add up to the dimension of the element. Unfortunately, all the CSS enabled versions of IE before IE 6 do not follow this box model. In this model, any padding and border would be added within the original dimensions of the element leading to a narrow rendering of the box. This causes a major problem in the page layout. Well in absence of padding and borders both the models work similarly.

Take a look at an example to make this clearer-

{width: 200px; padding: 5px; border: 5px;}

The ‘standards’ browser the dimension of the box would be calculated as 200 + 5 + 5 + 5 + 5 = 220px. But in IE 5 or earlier versions, since these values are put inside the original width, the dimension would be 200px only and the contents would be squeezed to fit in.

The hack

The box model hack uses the bugs in IE to use CSS tags which will be ignored by other browsers. I have explained one hack in this article. Let us consider the above example in detail.

To add a <div>

div {

                width: 200px;

                padding: 5px;

                border: 5px black solid;

}

The standards’ browser will interpret this code as 220px wide div element and IE will calculate it as 200px. To fix this, you need to define 2 <div>, one defines width as 200px to all the standards compliant browsers and the other defines width for IE as 220px.

div {

                width: 200px; //For standards compliant browsers like Mozilla, Opera 5, that throttle on the escapes used below.

}

div {

                \width: 220px; //Sets IE 5 and IE 6 quirks mode to 220px width.

                w\idth: 200px; //For all the modern browsers including IE 6 non quirks mode, which can render the width correctly.

}

Filed Under: CSS Hacks, Tips and Tricks

About the Author: Minal is a freelance web and graphics designer. She specializes in designing Logos, Stationery, Graphics and Icons as well as website templates using graphical tools like Photoshop, Illustrator and Expression Web. Twitter @saffronstroke

RSSComments (2)

Leave a Reply | Trackback URL

  1. Shreyo says:

    a picture say thousand words… i’d prefer a image of the result of the code.

Leave a Reply