First post on this platform :)
I'm currently having an issue with percentage positioning. The style and the computed style are showing a different value for the top property of my element:
- the value I see in the computed style is in pixels instead of in % as defined in the stylesheet
- the value is different: if I replace the style with the computed style, the element moves down of about 40 pixels.
Here is my code:
<div id="container">
<img id="img1" />
<img id="img2" />
</div>
#container { position:relative; display:inline-block;}
#img1 { position:relative; }
#img2 { position:absolute; top:40% }
img1 is 600px high. Since it has a relative positioning, container gets its height. So container is 600px high. If I do the math, top position of #img2 in pixels should be 240px.
But computed style is giving me 280px. Why?
This thing happens for almost all children in my container and it is driving me nuts!
Does anyone have an idea of what's happening?
From MDN:
Computed style values will always be absolute values as they represent the state of a given element after the browser has finished applying CSS.
Edit
Now that you've provided code, I can answer your specific issue.
Set
display: blockon#containerand your images.The computed value is relative to the containing document, not to the immediate parent of the element. If you take a screenshot and measure the distance from the top of
#containerdown to the top of#img2you should see that it's correctly 240px. However, the computed value oftopfor#img2won't necessarily be 240px.Here's a demo. The blue rectangle is absolutely positioned at
top: 40%;which correctly renders 240px down in its 600px container, but if you look at the computed value fortopit'll report a different value because it's relative to the top of the viewport, which has margins set on the body.