Cross Browser offsetWidth

I am having a problem using offsetWidth for different browsers. This difference in results causes some weird layouts. I created a very small example that displays what I see.

jsbin

HTML

<table id="tbl"> <tr> <td>Cell 1</td> <td>Cell 2</td> </tr> </table> <button onclick="calc()">Calculate Offset Width</button> <div>Cell 1 offsetWidth: <span id="c1offWidth"></span></div> 

Js

 function calc(){ document.getElementById('c1offWidth').innerHTML = document.getElementById('tbl').children[0].children[0].offsetWidth; } 

CSS

Eric Meyer Reset CSS

When I run it on chrome, safari and opera, the value returned for cell offset width 1 is 72. When I run this on firefox and IE9-10, the return value is 77.

I got the impression that this was the best way to calculate the width of an element, including padding and border.

Is there a cross-browser solution that will always return the same result? I tried using jQuery, but the results were even more confusing.

EDIT Because everyone recommends outerWidth, I did jsbin too. Results still vary across browsers. Chrome returns 36; IE9-10 and Firefox return 39.

updated jsbin

+7
source share
4 answers

Since you checked the jQuery post, I assume the jQuery solution is acceptable. What happened to outerWidth() ?

For example:

 function calc() { var the_width = $('#tbl tr:eq(0) td:eq(0)').outerWidth(); $('#c1offWidth').html(the_width); } 

Using jQuery brings a number of advantages to the table (as you can see due to the reduced amount of code needed above). You should also consider using non-intrusive event handlers. For example, remove the onclick attribute from your button and do the following:

 $(function() { $('button').click(function() { var the_width = $('#tbl tr:eq(0) td:eq(0)').outerWidth(); $('#c1offWidth').html(the_width); }); }); 

See jsFiddle demo .

+4
source

The actual problem in your example was that different browsers use different default fonts for rendering. And the cell size for your cells is determined by the content. If you set a specific width for the element (as correctly indicated in one of the comments), you will get a specific and equal result.

ps: cannot leave comments ...

+4
source

offsetWidth not a reliable cross browser. I would recommend using jQuery outerWidth() instead.

 $("#your-element").outerWidth(); 

See DEMO .

+3
source

You can use jQuery .outerWidth() if you need to get the estimated width between browsers, including such as borders and margins.

0
source

All Articles