Why does 'padding' sometimes count inside an element width, and sometimes not?
I've made a bookmarklet that, among other things, loads a form in a "popup" div. I reset every CSS tag known to mankind on every element I create, and as far as I can tell examining it in firebug, no CSS tag is "bleeding through". However, on some pages, the input width includes its padding:
input.clientWidth = input.style.width
on other pages, the input width does not include the padding:
input.clientWidth = input.style.width + input.style.paddingLeft + input.style.paddingRight
As such, here is a small code snippet:
开发者_StackOverflowinput.style.width = '300px';
input.style.border = '1px solid grey';
input.style.padding = '20px';
alert(input.clientWidth);
On some pages, this alerts 298 (300 - the 1px border), and on other pages this alerts 338 (300 - the 1px border + 20 + 20). What causes this? And more importantly, what can I do to get consistent behavior?
Edit:
This is all in the same browser - Firefox 3.6.8
For IE it could be that some pages are in quirks mode where the box model is not the standard one used.
The document.compatMode
would be CSS1Compat
for standards mode and BackCompat
for quirks mode. You can branch out the calculation based on that.
Obviously it would help if you showed us two separate pages that vary, but since it's a bookmarklet and it's invoked on different sites it would make sense.
For consistent behavior, you can factor the padding, margin and border into every width, i.e. (pseudocode)
totalWidth = input.width + input.padding + input.margin + input.border;
Obviously, you have to do some string manipulation to pick out the integers there and then add them.
精彩评论