SivaRajini
SivaRajini

Reputation: 7375

Position absolute and position relative

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

Upvotes: 1

Views: 1575

Answers (2)

MDEV
MDEV

Reputation: 10838

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/

Upvotes: 1

Christian Gray
Christian Gray

Reputation: 11

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.

Upvotes: 1

Related Questions