Difference between relative and absolute positioning


Difference between relative and absolute positioning

Difference between relative and absolute positioning

Difference between relative and absolute positioning

Relative Positioning

  • When position:relative is given to an element without any other attributes (top, bottom, left, right) nothing will happen.
  • But when an attribute left:20px is added the element moves 20px to the right from its normal position. The element effects no other element on the layout. Other content will not be adjusted to fit into any gap left by the element.
  • The child of this element can be positioned within this block only. So position:relative has its limitations.

Position Relative

HTML CODE

<!doctype html>
<html>
<head>
<title>DIFFERENCE BETWEEN POSITION RELATIVE AND POSITION ABSOLUTE</title>
<link href="example.css" rel="stylesheet">
</head>
<body>
  <div id="a1">FIRST</div>
  <div id="a2">SECOND</div>
</body>
</html>

CSS CODE

@charset "utf-8";
/* CSS Document */
#a1	{
  width:304px;
  height:154px;
  background-color:white;
  border:2px solid blue;
  position:relative;
  text-align:center;
}
#a2	{
  width:304px;
  height:154px;
  background-color:white;
  border:2px solid orange;
  top:70px;
  left:30px;
  position:relative;
  text-align:center;
}

Absolute Positioning

  • When position:absolute is given to an element the element can be placed precisely where one wants to.
  • The element is positioned nearest to the first relatively or absolutely positioned parent element.
  • When there is no parent element the absolutely positioned element is positioned directly to the HTML page itself.

Position Absolute

HTML CODE

<!doctype html>
<html>
<head>
<title>ABSOLUTE POSITIONING</title>
<link href="example1.css" rel="stylesheet">
</head>
<body>
  <div class="a1">
  <div class="a2"></div>
  </div>
</body>
</html>

CSS CODE

@charset "utf-8";
/* CSS Document */
.a1	{
  width:304px;
  height:304px;
  background-color:white;
  border:3px solid blue;
  text-align:center;
  position:relative;
}
.a2	{
  width:154px;
  height:154px;
  background-color:white;
  border:3px solid orange;
  text-align:center;
  position:absolute;
  top:100px;
  left:40px;
}

For more details about HTML CSS

Article written by HARSHAL ARORA

8368443489

9873405903

arora.harshal@gmail.com

Contact me on Facebook