Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between relative and absolute [duplicate]

Tags:

css

I'm reading this article about position, and I don't understand why in this example the relatively positioned div is affected by the BODY, yet the absolutely positioned box ignores it?
Aren't they suppose to behave the same when they are positioned inside another element?

the CSS:

body {
     display: block;
     margin: 8px;
}

#box_1 { 
     position: relative;
     width: 200px;
     height: 200px;
     background: #ee3e64;
}
#box_2 { 
     position: absolute;
     top: 0;
     left: 100px;
     width: 200px;
     height: 200px;
     background: #44accf;
}
like image 828
ilyo Avatar asked Aug 09 '11 14:08

ilyo


2 Answers

Basically you have four position states, which are as follows:

  • static (default)
  • relative
  • fixed
  • absolute

The difference between relative and absolute is that relative is "relative" to itself (left:15px will pad it to the left with 15px), but absolute is relative to its parent (first non-static parent that is) and applying the same attribute (left:15px) will result in it being shifted 15px away form the left edge of the parent element.

This is actually a fascinating study and will help immensely in understanding web layout.

like image 59
Joseph Marikle Avatar answered Nov 15 '22 12:11

Joseph Marikle


Here is the easy explanation of position: absolute and position: relative.

With absolute position, we can move an html element anywhere on the page.If we do not define any position element then it will take position from body element otherwise it will take it's position from the nearest defined position element. Below is the example.

In this case, 'div2' takes the position from 'div1' element.

<div id='div1' style="position: relative; left: 100px;top: 10px;"> 
<h1>This is the first position element</h1>
<div id='div2' style="  position: absolute;left: 100px;top: 150px;">
<h2>This is a heading with an absolute position</h2>
</div>
</div>

In this case 'div2' takes position from body elements as no position is defined.

  <div id='div1'> 
    <h1>This is the first position element</h1>
    <div id='div2' style="  position: absolute;left: 100px;top: 150px;">
    <h2>This is a heading with an absolute position</h2>
    </div>
    </div>

With relative position, an html elements can move from it's normal position.Below is the example.

In this case it will move from it's postion 10px left and 10px below.

<div id='div2' style="  position: relative;left: 10px;top: 10px;">
<h2>This is a heading with an absolute position</h2>
</div>
like image 27
Sheo Dayal Singh Avatar answered Nov 15 '22 12:11

Sheo Dayal Singh