CSS positioning

In this article we are going to understand CSS positioning.

CSS positioning

Positionings

There are mainly 5 positions are there,

  • Static

  • Relative

  • Absolute

  • Fixed

  • Sticky

    position: static

    This is the default position in CSS we can't use properties like top, right, bottom, left, and Z-index properties.

output: By browser default, we can see static position.

Below code was HTML code.

<body>
  <div class="b1"> Box 1</div>
  <div class="b2"> Box 2</div>
</body>

Below you can see the CSS code

body{
    text-align: center;
    color: aliceblue;
}
.b1{
    height: 200px;
    width: 200px;
    background-color: blue;
}
.b2{
    height: 400px;
    width: 400px;
    background-color: red;
}

position: relative

Here the element is positioned according to the flow of the document, and it is controlled by properties like top, bottom, left, and right.

body{
    text-align: center;
    color: aliceblue;
}
.b1{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: relative;
    top: 100px;
}
.b2{
    height: 400px;
    width: 400px;
    background-color: red;
}

Output:

The HTML code remains the same, next I applied position relative to the blue box and gave a property of 100px top so it moves from the top of 100px to its original related position

position: absolute

Here the element is removed from the normal document flow, and it is positioned relative to its parent element. and its final position is determined by its properties like top, bottom, right, and left.

body{
    text-align: center;
    color: aliceblue;
}
.b1{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: absolute;
    top: 100px;
    left: 100px;
}
.b2{
    height: 400px;
    width: 400px;
    background-color: red;
}

Output:

position: fixed

This element removes the flow from the document, after the properties like left, right, top, and bottom. it is fixed to the assigned value and it doesn't change the position.

body{
    text-align: center;
    color: aliceblue;
}
.b1{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: fixed;
    top: 100px;
    left: 100px;
}
.b2{
    height: 1500px;
    width: 480px;
    background-color: red;

}

output: Here You can see I am scrolled down a lot but the blue box stays there only, it will not moves when we use a fixed position.

position: sticky

This element is positioned according to the flow of the document, and after giving properties to elements it changes the position and sticks to the assigned value.

body{
    text-align: center;
    color: aliceblue;
    background-color: black;
}
.b1{
    height: 200px;
    width: 200px;
    background-color: blue;
    position: sticky;
    top: 50px;

}
.b2{
    height: 1000px;
    width: 480px;
    background-color: red;

}

output: Below you can see the output in which the blue box sticks about the top of 50px when we scroll.