Saturday, February 14, 2015

CSS Layout - Relative and Absolute Position

CSS Layout - Relative and Absolute

The position property is crucial to CSS layout. It has a couple of possible values. This article gives a simple example to help you understand the two most important values: relative and absolute.

CSS Sample

<style type="text/css">
.relative1 {
  position: relative;
  border: 1px solid red;
  color: red;
}
.relative2 {
  position: relative;
  top: -20px;
  left: 20px;
  width: 500px;
  border: 1px solid green;
  color: green;
}
.relative3 {
  position: relative;
  border: 1px solid orange;
  color: orange;
}
.absolute1 {
  position: absolute;
  top: -20px;
  left: 20px;
  width: 500px;
  border: 1px solid blue;
  color: blue;
}
.absolute2 {
  position: absolute;
  top: -20px;
  left: 20px;
  width: 500px;
  border: 1px solid black;
  color: black;
}
</style>
<div style="margin: 30px">
<div class="relative1"><p>relative1</p><p></p><p></p></div>
<div class="relative2"><p>relative2</p><p></p><p></p></div>
<div class="absolute1"><p>absolute1</p><p></p><p></p></div>
<div class="relative3"><p>relative3</p>
<div class="absolute2"><p>absolute2</p><p></p><p></p></div>
</div>
</div>


CSS Rules


There are two rules to remember:
  1. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. In the example above, relative2 should be under relative1, however, since we set its top and left properties, it goes higher and to the left of its normal position. 
  2. A absolutely-positioned element is positioned relative to the nearest positioned ancestor (container). If an absolutely-positioned element has no positioned ancestors, it uses the document body. In the example above, absolute2 use relative3 as ancestor and adjusts accordingly. While absolute1 does not have an ancestor, so it adjusts according to the document.


Create a Successful Online Store at Bigcommerce! Try it Free Now!

No comments:

Post a Comment