Css Positioning

Position Properties

One of the most important skill in the Css World is the ability, to move an element from one point to anywhere around the browser, It make a developer feels like superman handling a keyboard.

Imagine you can be an Avatar who could ask element to move to anywhere you want, but not outside the playing environment which is your browser.

Css Position properties help you set how an element is position in a document. There are five major methods we can apply while positioning our elements.

  • Static Positioning

In this type of position the element is placed according to the normal document flow but it remains unmovable even when value like top, left, right, bottom and z-index.

  • Absolute Positioning

Elements that are relatively positioned remain in the normal flow of the document. In contrast, an element that is absolutely positioned is taken out of the flow; thus, other elements are positioned as if it did not exist. The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static). If a positioned ancestor doesn't exist, it is positioned relative to the ICB (initial containing block — see also the W3C definition), which is the containing block of the document's root element. (MDN)

  <div class="book" id="one">One</div>
    <div class="book" id="two">Two</div>
    <div class="book" id="three">Three</div>
    <div class="book" id="four">Four</div>
  .book {
  display: inline-block;
  width: 70px;
  height: 70px;
  background: green;
  color: white;
}

#two {
  position: absolute;
  top: 30px;
  left: 30px;
  background: black;
}
  • Relative Positioning

In this type of position the element is placed according to the normal document flow and it can be moved by to the preferred direction by applying value like top, left, right, bottom and z-index. When relative position is applied to an element, the element is offset a specific distance from their normal position within the document.

  <div class="book" id="one">One</div>
    <div class="book" id="two">Two</div>
    <div class="book" id="three">Three</div>
    <div class="book" id="four">Four</div>
  .book {
  display: inline-block;
  width: 70px;
  height: 70px;
  background: green;
  color: white;
}

#two {
  position: fixed;
  top: 0;
  left: 0;
  background: black;
}
  • Fixed Positioning

    The fixed positioning is similar to the absolute positioning also but the only thing that differentiate the fixed from absolute is the ability to stay put when other element in the page are moving.

  .book {
  display: inline-block;
  width: 70px;
  height: 700vh;
  background: green;
  color: white;
}

#two {
  position: fixed;
  top: 0;
  left: 0;
  background: black;
}