Search code examples
javascriptobjectmethodswindow

window.getComputedStyle always returns measurement in pixels


I am just wondering why, for instance, window.getComputedStyle(element).top always returns the measurement in pixels, even in cases whereby the top position is set explicitly to % like so element.style.top = 25 + '%'.

I have not been able to find any information online. Anybody know why this is the case?!


Solution

  • What you're looking for is element.style.top.


    That is the intended behaviour of window.getComputedStyle.

    "The window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain."

    Meaning that everything that is a unit other than pixels will be calculated or processed and then presented as pixels. Even the name GetComputedStyle hints that.

    You can read more about this here if you want.