1

I am confused about position absolute and relative in CSS.

<div id="container" style="position:"relative"> <button style="position:"absolute"; left:10px;" > </div>

In the above example, when I set position as absolute and left as 10px to button means it doesn't takes the position from browser window. Instead of this, it takes position from parent div (container) because container position is relative. Why?

When I set position absolute to any element it takes the position from browser window only. Why it checks the parent element and then positioning.

When I set position relative to any element means that time it will position based on parent element.

<p>Paragraph 1.</p> <p>Paragraph 2.</p> <p style="position: relative;left: 2em;">Paragraph 3.</p>

In the above example, the third paragraph will be positioned 3em from the left side of the container element.

I have researched following links.

http://webdesign.about.com/od/advancedcss/a/aa061307.htm

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

absolute → takes position from browser window

relative → takes position from parent of an element

1
  • 1
    You are correct. If you place an absolutely-positioned element inside of a relatively-positioned element, the inner element positioning is based on the parent. Not exactly sure why this is the case, but this is how it works. Also remember that absolute positioning takes an object out of the flow; the relative parent just helps establish the 0,0 coordinates, essentially. Commented Jun 19, 2013 at 16:49

2 Answers 2

1

An absolute position element is positioned relative to the first parent element the position of which isn't static. If such element is not found, the containing block is html element.

Sign up to request clarification or add additional context in comments.

Comments

1

Absolute

Positioned relative the first parent element that is relative or absolute (defaults to html/browser window) - meaning that having a relative parent, causes all child elements to be positioned relative to that element when using absolute

Relative

Positioned relative to it's original static position (parent not involved) - can be used to slightly move an element from it's current position, without affecting the elements' layout

Fixed

Depending on your usage requirements, another option is position:fixed which keeps the item positioned relative to the browser window, regardless of parent styling (useful for modal windows, as the element stays where it is, even when scrolling)

Extra reading: http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.