CSS Positions

Lets take a look at different types of CSS positions. I have created Sandbox to understand and playaround with the CSS positions. Total there are five types of positions.

  1. Static
  2. Relative
  3. Absolute
  4. Fixed
  5. Sticky

    Below is the screenshot of end result which we are going to use to understand the position property, we have parent container with blue border.Inside this parent we have three children and this parent container is set to relative position always.

css position.png

  • Static:

    This is default property of the element and we can not apply additional position property which we are going to see in the other types.

  • Relative:

    The relative property is behaves similar to stative but we can apply additional property like top, bottom, left, right and z-index as shown below. We have set child-1 element to relative, moved 50px from top of the parent box i.e from blue border and moved 20px from left of the blue border. z-index is set to 0 which is default property with no change in the visibility.

    #child1 {
    background-color: red;
    position: relative;
    top: 50px;
    left: 20px;
    z-index: 0;
    }
    
  • Absolute:

    Here we have set child-2 as absolute, giving 0px from top and 30px from right of the parent. One thing to notice here is the parent container is set to relative, hence the child element is bound within the parent container. If the parent is set to static this child-2 with absolute property will search for the outer container with relative property if not found it will treat root element as parent. We have set z-index to 1 which is more than other children hence the green box is visible on top of the child one.

#child2 {
  background-color: green;
  position: absolute;
  top: 0px;
  right: 30px;
  z-index: 1;
}
  • Fixed:

    If you look at the screen-shot we have set navbar container as fixed with z-index 10. This will keep this container on top of the screen always even when we scroll down. You can check this behavior on the . Sandbox
    <div class="navbar"><h1>CSS Positions</h1></div>
    
.navbar {
  width: 100%;
  position: fixed;
  z-index: 10;
}

fixed.png

  • Sticky:

    When child-3 is set to sticky, this works similar to fixed property but child-3 will be in initial position but when we reach on bottom of the screen this child-3 will stick to top at 10px from parent box.
#child3 {
  background-color: yellow;
  position: sticky;
  top: 10px;
}

sticky.png

I would suggest to visit the Sandbox and playaround to understand more about the positions. If you think there is need to modify/change anything please leave a comment.

Thank You, Gandharva R (GD)