Friends

Monday, November 7, 2011

CSS Box Model

What is the box model? The basics of CSS positioning starts with understanding the CSS Box Model. Every HTML element in a document is a rectangular box as shown below.
2 (3K) Margins are always transparent. They seperate the box from surrounding elements. They do not contribute to the width of the box.
Borders come in various styles. They do not contribute to the width of a box.
Padding seperates the actual box content from the borders. They do not contribute to the width of the box.
Content is the portion in white in the above image. The width of the content is the width of the box.
So if we are to calculate the CSS Width of a box it would be
CSS Width = Content Width
Provided you use a valid doctype, most modern browsers understand the above box model. The exception to the rule is Internet Explorer 5 upto Internet Explorer 6. IE 6 and above get the box model right with a valid doctype.

Internet Explorer 5 Box Model

In Internet Explorer 5 border and margin contribute to the width of the box. Consider the following div
Code:
#example { width: 300px; border: 10px; padding: 15px; margin: 25px; } For the above CSS, the diagram below shows how a standard browser renders the box in comparision to IE 5
1 (7K) IE 5 considers the width 300px inclusive of border and padding, hence for IE 5,
IE Width = Left Border + Left Padding + Content Width + Right Padding + Right Border
OR
300px = 10px + 15px + Content Width + 15px + 10px
SO
Content Width = 300px - 10px - 15px - 15 px - 10 px = 250px
If we have to have a content width of 300px, then IE Width would be
IE Width = 10px + 15px + 300px + 15px + 10px = 350px. Our style should be
Code:
#example {
width: 350px;
border: 10px;
padding: 15px;
margin: 25px;
}
Now its time to combine the 2 widths and feed the correct browser the correct width
Code: <style>
#example {
width: 300px; /* for standards based browsers */
border: 10px;
padding: 15px;
margin: 25px;
} </style>
<!--[if IE 5]>
<style>
#example {
width: 350px; /* for IE 5 */
}
</style>
<![endif]-->

0 comments:

Post a Comment

#
### ###