What is the difference

Hello World,

Please what is the difference between ABSOLUTE and RELATIVE position?

Its a little bit subtle when you’re not used to how it works, so given this example:

Both examples have two paragraphs, with the first one positioned, and the second one just left as the default “static” position. The positioned paragraph has been moved down by 20px in both (using top:20px).

The position relates to the document flow - by document flow, I mean that by default, the elements will appear in the page in the order you put them in the HTML, one after the other. position allows you to fiddle with this.

The first one is relative: that gap at the top is where the element is in the document flow. That hasn’t changed, the second paragraph follows the first paragraph, but the element itself has been shifted down.

The second one is absolute: there is no gap because what absolute does is remove the element from the document flow - it’s as if that paragraph isn’t there any more, and it doesn’t affect any other elements. When you move it around, it just sits over the top of everything else.

This is a bit abstract and a bit hard to grasp I think, here are some supporting articles:

http://www.barelyfitz.com/screencast/html-training/css/positioning/


Probably the most common way you see this used relies on how the two things work together. position: absolute says "position this element relative to the nearest parent with position:relative". So if I have an element, and I want one of the child elements in a specific place in that element, I can set relative on the element, and absolute on the child I want to position, and I can now say exactly where I want to move that child to inside the parent. If that seems a bit abstract:

Say I have a modal, with a close button. I want the close button at the top right of the modal. All the other stuff in the modal I just want as normal - some text, a button or two. So I apply position:relative to the modal. Then I give the close button position:absolute, and top:0 and right:0, and now it sits at the top right of my modal.