admin管理员组

文章数量:1304182

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?!

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?!

Share Improve this question edited Mar 16, 2023 at 17:15 djvg 14.4k7 gold badges83 silver badges115 bronze badges asked Dec 29, 2017 at 0:39 oldboyoldboy 5,9647 gold badges42 silver badges99 bronze badges 5
  • 1 because relative input values have to be calculated to pixels for monitor display. If you want % you need to calculate it based on parent container dimensions – charlietfl Commented Dec 29, 2017 at 0:43
  • @charlietfl that makes sense. thanks! – oldboy Commented Dec 29, 2017 at 0:44
  • Similar with the variety of color formats...they get converted and you get back rgb even when you input hex or other format values – charlietfl Commented Dec 29, 2017 at 0:48
  • @charlietfl yeah, i noticed that one ages ago. that one always caused me issues lol – oldboy Commented Dec 30, 2017 at 16:39
  • It does not always return pixels. For example, window.getComputedStyle(element).gap returns a % value if defined as such. (at least it does in firefox) – djvg Commented Mar 16, 2023 at 17:28
Add a ment  | 

1 Answer 1

Reset to default 10

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 putation 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.

本文标签: javascriptwindowgetComputedStyle always returns measurement in pixelsStack Overflow