Best way to solve the 'padding' css problem

21,984

Solution 1

The IE box model (known as the traditional box model), includes the padding and border in the width/height of an element.

Under the IE box model, a box having a width of 100px, with 2px padding on each side, a 3px border, and 7px margin on each side, will have a visible width of 114px.

The W3C box model (which is the standard box model), excludes the padding and border from the width/height of an element.

Under the W3C box model, a box having a width of 100px, with 2px padding on each side, a 3px border, and 7px margin on each side, will have a visible width of 124px.

Box Models
(source: 456bereastreet.com)


In order to make IE use the W3C box model (which is what every other browser uses), your page needs to be rendered in Strict mode. By default, IE renders in Quirks mode.

In order to trigger Strict mode in IE, you must specify a doctype. You can use any of the following doctypes:

HTML4 Strict:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd" >

XHTML 1.0 Strict:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

XHTML 1.0 Transitional:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Your doctype must be the first thing to appear on your page. It is even before the <html> tag, on its own line.

More information about Quirks/Strict mode here:

CSS - Quirks mode and strict mode

Solution 2

Another option is to put in a conditional comment for a particular browser you're having trouble with for example:

<!--[if IE 6]>
     <style type="text/css">
          #thisdiv { width:500px; height:500px; padding:50px; }
     </style>
<![endif]-->

I'm not sure this is the best way but I don't think anyone has this really figured out. I think we all just do our best and hope that things get better over time so this stuff isn't needed.

Solution 3

Not only are the behaviors different between Firefox and IE...they're different even between the different versions of IE.

The best approach is to use CSS selectors rather than inline styles and use IE conditional comments to load different stylesheets based on browser version. It allows you to create one master stylesheet and then fix any anomolies in the others.

Share:
21,984
Sina Meftah
Author by

Sina Meftah

Updated on April 03, 2020

Comments

  • Sina Meftah
    Sina Meftah about 4 years
    <div style='width:500px; height:500px; padding:50px;'> </div>
    

    As the behaviors of 'padding' on IE and Firefox are different. What is the best way to solve this problem?