CSS Position

Home / CSS / CSS Position

CSS Position


CSS Position:

In CSS, the position property is used to control the positioning of an element within its containing element. The position property can take several values, each of which determines how an element is positioned on the web page. Here are the most common values for the position property:

static:

This is the default value. Elements with position: static; are positioned in the normal document flow. The top, right, bottom, and left properties have no effect on static elements.

 
<style>
    div {
      position: static;
    }
  </style>

relative:

Elements with position: relative; are positioned relative to their normal position in the document flow. You can use the top, right, bottom, and left properties to move the element from its normal position without affecting the layout of other elements.

<style>
    div {
      position: relative;
      top: 20px;
      left: 10px;
    }
  </style>

absolute:

Elements with position: absolute; are positioned relative to their nearest positioned ancestor (an ancestor with position set to anything other than static) or the initial containing block if there's no such ancestor. This can be used to create elements that are removed from the normal document flow.


<style>
    div {
      position: absolute;
      top: 50px;
      left: 50px;
    }
  </style>

fixed:

Elements with position: fixed; are positioned relative to the viewport (the browser window). They stay in the same position even when the page is scrolled. Fixed elements are often used for navigation bars or elements that should always be visible.

<style>
    header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background-color: #333;
      color: #fff;
    }
  </style>

sticky:

Elements with position: sticky; behave like relative until they reach a specified scroll position, after which they become fixed. This is often used for headers or navigation bars that "stick" to the top of the viewport when scrolling down.

<style>
    header {
      position: sticky;
      top: 0;
      background-color: #333;
      color: #fff;
    }
  </style>