Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do browsers replace the width value assigned via css?

When I assign a basic style to all selects eg.

width: 300px;
padding: 0;
margin: 0;
border-width: 1px;

I get unexpected results when retrieving the width via javascript under different circumstances.

  • When the select is visible the with is 298px.
  • When the select is display:none, the width is also 298px (ff, jquery)
  • When the select is in a div with display:none, the width is correct 300px.

(The result is also the same assigning: box-sizing: border-box)

Well, the retrieved width sometimes differs from the used browser and javascript framework, but all in all I just want to be able to retrieve the assigned width (300px). (I guess it has to something to do with the "formal weirdness" stated here: http://meyerweb.com/eric/thoughts/2007/05/15/formal-weirdness/, but why won't the browsers use the width assigned by the user??)

How can I retrieve the assigned width? Is there actually way to do it?

Examples:

http://jsfiddle.net/ETCcH/5/ (for using jquery, or replace the 5 with a 4 for an example using mootools)

(view and try it with different browsers)

like image 906
Marc Avatar asked Oct 08 '22 17:10

Marc


2 Answers

Actually it is the borders that is causing you the trouble. Set the border-width to 0 and you will be able to see 300px for everybody. Actually the browsers are setting the element's width to 300px as you are expecting it to be, and adding the borders around. For visible elements you can get the entire width of the element by using offsetWidth (which will be set to 0 if you set the display to none.)

like image 36
mmg666 Avatar answered Oct 10 '22 07:10

mmg666


You will never get the value written down in the css file. With JavaScript you will only get the css properties currently applied to that element by the web browser.

In you case if the width is really fixed, you can "force" it with max-width set to 300px or adding an overflow: hidden - if that's an option.

like image 185
acme Avatar answered Oct 10 '22 08:10

acme