Search code examples
javascripthtmlpositioning

Issues with offsetTop when HTML margin is applied


if I set this CSS

html {
    margin: 10px;
    border 10px solid #ccc;
    padding: 10px;
}

and then try to get offsetTop of some element, is it possible to convince browsers (IE and CH) not to ignore document margin in the calculation? Firefox works as expected reporting values according to rendered HTML (uses all three values).

Is there a fast cross-browser way of calculating offsetTop when offsetParent is actually BODY. Unfortunately jQuery's .offset() doesn't do the trick here :(


Solution

  • This code will get you thinking and started.

    The idea is to use HTMLElement.getBoundingClientRect() function that's supported by all major browser these days (and has been for quite some time now). The only difference I've found out was when running it against document.documentElement element. FF and Chrome don't report bottom values according to view port but rather to whole document itself.

    So be careful.