Cécile Boucheron
Cécile Boucheron

Reputation: 659

Positioning: style and computed style have different values

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:

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?

Upvotes: 2

Views: 3822

Answers (1)

Andr&#233; Dion
Andr&#233; Dion

Reputation: 21758

From MDN:

getComputedStyle() gives the final used values of all the CSS properties of an element.

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: block on #container and 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 #container down to the top of #img2 you should see that it's correctly 240px. However, the computed value of top for #img2 won'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 for top it'll report a different value because it's relative to the top of the viewport, which has margins set on the body.

Upvotes: 0

Related Questions