Does element width include padding?
IE used to use the more-convenient-but-non-standard "border-box" box model. In this model, the width of an element includes the padding and borders. For example:
#foo { width: 10em; padding: 2em; border: 1em; }
would be10em
wide.In contrast, all standards-fearing browsers default to the "content-box" box model. In this model, the width of an element does not include padding or borders. For example:
#foo { width: 10em; padding: 2em; border: 1em; }
will actually be16em
wide:10em
+2em
padding for each side, +1em
border for each edge.
If you use a modern version of IE with valid markup, a good doctype, and appropriate headers it will adhere to the standard. Otherwise, you can force modern standards-compliant browsers to use "border-box" via:
* {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
The first declaration is needed for Opera, the second is for Firefox, the third is for Webkit and Chrome.
Here's a simple test I made years ago for testing what box-sizing declaration your browser supports: http://phrogz.net/CSS/boxsizing.html
Note that Webkit (Safari and Chrome) do not support the padding-box
box model via any declaration.
A simple rule is to try to avoid using padding/margin and width property for same element. i.e. Use something similar to this
<div class="width-div">
<div class="padding-div">
...........
...........
</div>
</div>
I bumped into this question and even though it's a couple of years old, I thought I might add this in case anyone bumps into this thread.
CSS3 now has a box-sizing property. If you set, say,
.bigbox {
box-sizing: border-box;
width: 1000px;
border: 5px solid #333;
padding: 10px;
}
your class will be 1000px wide, instead of 1030px. This is, of course, incredibly useful for anyone who uses pixel-sized border with liquid divs, because it solves an otherwise insoluble problem.
Even better, box-sizing is supported by all major browsers except IE7 and below. To include all items within the width or height dimension, set box-sizing to border-box. To aggregate other items to the width and/or height, which is the default, you can set box-sizing to "content-box".
I'm not sure of the current state of browser syntax, but I still include -moz and -webkit prefixes:
.bigbox{
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
Do you have a doctype declared? When I started coding html I had this problem, and it was from not having a doctype declared. My favorite is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
...
</html>
for those who would still have the problem, jQuery provided two property outerWidth ()
and innerWitdh ()
to know the width of an object with or without borders ...