CSS Position Property

A web page has a number of HTML elements and sometimes different elements need to align a different kind of positioning for better page layout.

The CSS position property is used to specify the type of positioning for HTML Elements.

Type of CSS position properties

You can use four different positions for elements.

  • Static
  • Relative
  • Fixed
  • Absolute

We will learn about each of them with example.


CSS Position Static

This is the default position of HTML elements. A static position element according to the normal flow of the HTML page. There is no use of CSS top, bottom, left, and right properties if the HTML element has a static position.

<p>Next div is example of static html element</p>

<div style="position: static; border: 2px solid blue;">
This HTML div element has static position;
</div>

CSS Position Relative

HTML Element with Relative Position is positioned relative to its normal position. By default relative positioning works similar to static unless positioning you add some extra properties. You can use the CSS top, bottom, left, and right properties to move the element from the adjacent element accordingly.

<p>Next div is example of static html element</p>

<div style="position: relative; border: 2px solid blue; left: 20px; bottom: 20px;">
This div element has position relative;
</div>

CSS Position Fixed

A CSS fixed element is positioned relative to the viewport or browser window. Fixed positioned element always stays in the same place even if you scroll the page.

You can use CSS top, bottom, left, and right properties to fix element somewhere in the browser.

<div style="position: fixed; border: 2px solid blue; top: 20px; right: 0px;">
This HTML div element has fixed position;
</div>

CSS Position Absolute

A CSS absolute element is positioned relative to the first parent element. If there is no parent element, position will be related to the page. Therefore, absolute positioned element works like fixed but its position is related to nearest positioned parent (ancestor) instead of relative to the viewport window.

You can use CSS top, bottom, left, and right properties to fix element related to the parent element.

<div style="position: relative; border: 2px solid blue; left: 20px; width: 400px; height: 200px;">
  This is parent element of next element.
    <div style="position: absolute; border: 2px solid blue; bottom: 20px; right: 0px;">
        This HTML div element has fixed position;
    </div>
<div>

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.