CSS Positions

Update

Add Subtitle

Article on Position in CSS

Write

Preview

Editor Guide

The Position property in CSS tells about the method of positioning for an element or an HTML entity. The position property can help you manipulate the location of an element, There are five different types of position properties available in CSS:

  • Fixed

  • Static

  • Relative

  • Absolute

  • Sticky


Fixed:

Any HTML element with position: fixed property will be positioned relative to the viewport. An element with fixed positioning allows it to remain at the same position even as we scroll the page. We can set the position of the element using the top, right, bottom and left.

Example: The below example illustrates the CSS positioning element by using the position: fixed property.

.fixed {
        position: fixed;
        background: green;
        color: white;
        padding: 30px;
        top: 50;
        left: 10;
    }

Static:

Every element has a static position by default, so the element will stick to the normal page flow. So if there is a left/right/top/bottom/z-index set then there will be no effect on that element.

 .static {
        position: static;
        background: #cc0000;
        color: #ffffff;
        padding: 30px;
    }

Relative:

An element with position: relative is positioned relatively with the other elements which are sitting at top of it. If we set its top, right, bottom, or left, other elements will not fill up the gap left by this element. An element with its position set to relative and when adjusted using top, bottom, left, and right will be positioned relative to its original position.

 .relative {
        position: relative;
        background: orange;
        color: white;
        padding: 30px;
        top:100px;
        left:100px;
    }

Absolute

If a child element has an absolute value then the parent element will behave as if the child isn’t there at all. Absolute will be positioned with respect to its nearest Non-static ancestor. The positioning of this element does not depend upon its siblings or the elements which are at the same level.

.element {
  position: absolute;
  background: orange;
  color: white;
  padding: 30px;
  top:100px;
  left:100px;

}

Sticky

Element with position: sticky and top: 0 played a role between fixed & relative based on the position where it is placed. If the element is placed in the middle of the document then when the user scrolls the document, the sticky element starts scrolling until it touches the top. When it touches the top, it will be fixed at that place in spite of further scrolling. We can stick the element at the bottom, with the bottom property.

.sticky {
        position: sticky;
        background: orange;
        color: white;
        padding: 30px;
        top: 10px;
        right: 50px;
    }