Javascript – detecting true border, padding and margin from Javascript


Is there a way to detect the true border, padding and margin of elements from Javascript code? If you look at the following code:

        .some_class {
            padding-left: 2px;
            border: 2px solid green;
        function showDetails()
            var elem = document.getElementById("my_div");
            alert("elem.className=" + elem.className);
            alert("" +;
            alert("" +;
            alert("" +;
            alert("" +;
            alert("" +;
            alert("" +;
        <div id="my_div" class="some_class" style="width: 300px; height: 300px; margin-left: 4px;">
            some text here
        <button onclick="showDetails();">show details</button>

you can see, if you click the button, that the padding is not reported right. Only the properties defined directly through "style" are reported back, those defined through a CSS class are not reported.

Is there a way to get back the final values of these properties? I mean the values obtained after all CSS settings are computed and applied by the browser.

Best Solution

the style property can get the styles that are assigned inline like

<div id="target" style="color:#ddd;margin:10px">test</div> if you want to get the styles assigned in outer css file or <style/> element, try this:

var div = document.getElementById("target");
var style = div.currentStyle || window.getComputedStyle(div);
display("Current marginTop: " + style.marginTop);

if you are using jQuery, @vsync 's solution is fine.