BBog
BBog

Reputation: 3650

Why isn't the CSS relative positioning working correctly in this example?

I was doing some tests with CSS positioning and I noticed an odd behavior.

Let's say I have an absolutely positioned container div (red). Inside this div I want to place two blocks (green and blue), with a relative position to the container. These blocks should stick to the top and have a 50 pixels distance between them, like below

enter image description here

So I'm thinking I should use top:0px; left:0px; for the first one, to place him near the top left corner. I add 50 to its width for the spacing and I get top:0px; left: 100px; for the second block. (jsfiddle here).

Instead of seeing the expected behavior, I get this positioning

enter image description here

It seems that the second block has its toprelative to the first block, and not to the parent container. So the correct CSS code for the second block should be top: -50px; left: 100px;, like in this fiddle.

This isn't the first time I noticed this. In some cases, the left property it's the one at fault, in this case it was top.

Anyway, I know how to fix these problems and get the correct display, but I don't understand why isn't it working like I think it should.

It's very likely that I misunderstood something about this whole absolute/relative positioning, but I don't know what it is.

Upvotes: 2

Views: 236

Answers (1)

BoltClock
BoltClock

Reputation: 723388

The second block has its top and left relative to itself, not the first block or the parent container.

When you position something relatively, its offset values shift it in those directions away from what its original position would have been before you applied relative positioning. The offsets are never based on the positions of its siblings, ancestors or descendants (unless they are auto, which is their initial value).

Upvotes: 4

Related Questions