CSS Position

The CSS position property is used to set positions of different elements of HTML. There are many positions which can be applied to elements to make it looks good to the viewers. By using position property you can place an element to top, bottom, left, right, etc. So let's discuss what are the different position properties which are available in CSS.

Here is a code snippet, which displays three bars on the web.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .main{
            background-color:bisque;
            margin-left: 100px;
            margin-right: 100px;
            padding: 50px;
        }
        .one, .two, .three{
            text-align: center;
            padding: 8px 12px;
            background-color:aqua;
            margin: 10px;

        }
    </style>
</head>
<body>
    <div class="main">
        <div class="one">One</div>
        <div class="two">Two</div>
        <div class="three">Three</div>
    </div>
</body>
</html>

and this is the output, the position property isn't declared in the above code.

Screenshot (15).png

Now let us position this using CSS' different position properties.

1. Position: static
This is the default position of HTML element. And it positioned according to the normal flow of the document. We cannot change top, bottom, left, right and z-index values.

2.Position: relative
It works same as that of static but this this you are able to change the top, bottom, left and right properties of the elements. It changes the position relative to the parent element and relative to itself.

.one{
            position: relative;
            left: 10px;
        }

Output:

Screenshot (16).png

3.Position:absolute
By applying this property to respective element, that element will get removed from the flow of normal document. It allows you to position element related to the nearest positioned ancestor. The final position of the element can be determined by the values of top, bottom, left and right.

Example:

.two{
            position: absolute;
            right: 20px;
        }

Output:

Screenshot (17).png

4.Position:fixed By applying position:fixed to any element it gets positioned relative to the viewport, and it is also removed from the normal document flow. Also, no space is created for the element in the page layout. You can also determine its final position by the values of top, right, bottom and left.

Example:

.three{
            position: fixed;
            bottom: 25px;
        }

Output:

Screenshot (18).png