Search code examples
javascriptmargin

document.body.style.marginTop returning blank string in JS


It was my understanding that [some elem].style.maginTop would return a string with the element's top margin.

Instead, I'm always getting a blank string. I want to use this with the body, but I also tried on a div, and that didn't work either.

console.log(document.body.style.marginTop); // logs ""
console.log(typeof(document.body.style.marginTop)); // logs "String"

var elem = document.getElementById("testDiv");
console.log(elem.style.marginTop); // logs ""
body {
    margin-top:100px;
}
#testDiv {
    margin-top:50px;
}
hi!

<div id="testDiv">test</div>

I'm not sure what I'm doing wrong... Does anybody have a non-jQuery solution to this?


Solution

  • The HTMLElement.style only returns inline styles:

    The HTMLElement.style property returns a CSSStyleDeclaration object that represents the element's style attribute.

    To access the styles from stylesheets use Window.getComputedStyle(element):

    The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.

    var elem = document.getElementById("testDiv");
    var style = window.getComputedStyle(elem);
    
    //output
    document.body.innerHTML = style.marginTop;
    body {
        margin-top:100px;
    }
    #testDiv {
        margin-top:50px;
    }
    hi!
    
    <div id="testDiv">test</div>