When looking at the code of Lightbox.com I remarked that they are not using top
and left
in order to position their images but margin-top
and margin-left
. I've been wondering why for some time and finally found the reason.
It is a way to position absolutely elements in a container and preserving the padding property of the container.
Using traditional top
and left
As you can see, the position is relative to the top left of the container, completely ignoring padding.
padding: 20px;
top: 0;
left: 0;
top: 0;
left: 200px;
Using margin-top
and margin-left
And now, with this trick, the position is taking padding into account.
margin-top: 0;
margin-left: 0;
margin-top: 0;
margin-left: 200px;
padding: 20px;
Why it works?
When declaring an element position: absolute;
and not setting any of top
, right
, bottom
and left
, the element is going to be rendered using the normal flow for its position. However, it is not going to be added to the flow.
So if you want it to work, do not insert anything non absolute before the elements and make sure you don't set any of top
, right
, bottom
and left
.
Conclusion
This is a neat CSS trick but there's a little side effect when debugging. Inspectors are going to highlight the top left area of the element in orange which may be strange 🙂