I'm trying to read "marginTop" style property from the <html>
and <body>
tags. Chrome developer tools shows margin-top as set via in-HTML CSS:
<style type="text/css" media="screen">
html { margin-top: 28px !important; }
* html body { margin-top: 28px !important; }
</style>
However, when I try something like this:
console.debug(document.getElementsByTagName('html')[0].style.marginTop);
console.debug(document.getElementsByTagName('body')[0].style.marginTop);
I get empty strings in both cases.
jQuery's offset()
function detects margins correctly. Unfortunately, I cannot use jQuery in this case, it has to be pure JavaScript.
I would appreciate if someone could provide some insight on how I can read top margin property off the html and body elements.
You can solve it with:
var element = document.getElementsByTagName('html')[0],
style = window.getComputedStyle(element),
marginTop = style.getPropertyValue('margin-top');
jsFiddle
The document
already has knowledge about body
element, so:
window.getComputedStyle(document.body).getPropertyValue('margin-top');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With