Library tutorials & articles

Ten CSS Tricks You May Not Know

CSS box model

6. CSS box model hack alternative

The box model hack3 is used to fix a rendering problem in pre-IE 6 browsers on PC, where by the border and padding are included in the width of an element, as opposed to added on. For example, when specifying the dimensions of a container you might use the following CSS rule:

#box
{
width: 100px;
border: 5px;
padding: 20px
}

This CSS rule would be applied to:

<div id="box">...</div>

This means that the total width of the box is 150px (100px width + two 5px borders + two 20px paddings) in all browsers except pre-IE 6 versions on PC. In these browsers the total width would be just 100px, with the padding and border widths being incorporated into this width. The box model hack can be used to fix this, but this can get really messy.

A simple alternative is to use this CSS:

#box
{
width: 150px
}

#box div
{
border: 5px;
padding: 20px
}

And the new HTML would be:

<div id="box"><div>...</div></div>

Perfect! Now the box width will always be 150px, regardless of the browser!

7. Centre aligning a block element

Say you wanted to have a fixed width layout website, and the content floated in the middle of the screen. You can use the following CSS command:

#content
{
width: 700px;
margin: 0 auto
}

You would then enclose <div id="content"> around every item in the body of the HTML document and it'll be given an automatic margin on both its left and right, ensuring that it's always placed in the centre of the screen. Simple... well not quite - we've still got the pre-IE 6 versions on PC to worry about, as these browsers won't centre align the element with this CSS command. You'll have to change the CSS rules:

body
{
text-align: center
}

#content
{
text-align: left;
width: 700px;
margin: 0 auto
}

This will then centre align the main content, but it'll also centre align the text! To offset the second, probably undesired, effect we inserted text-align: left into the content div.

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of Ten CSS Tricks You May Not Know.

Leave a comment

Sign in or Join us (it's free).

AddThis

Related podcasts

  • Episode 3: Anne van Kesteren on CSS, XHR, and other Web standards

    Anne van Kesteren is an Opera Software employee who is deeply involved in the standards community. Just take a look at his page on the WHATWG site and you will see the many specifications that he is actively working on, such as: access-control XMLHttpRequest XMLHttpRequest2 cssom-view css3-media...

Events coming up

  • Dec 8

    Web Design World

    Boston, United States

    Join your colleagues and top experts in the Web field as Web Design World returns to Boston December 8-10, 2008 for three dynamic days of information, interaction, insight and inspiration.