When we create a webpage, every element comes one below another by default. But sometimes we need to move an element to a different place. For this, CSS provides the position property. It has five values: static, relative, absolute, fixed, and sticky. Each one works differently, so it is important to know when to use them.
1. Static Position
"static" is the default position of every HTML element. The elements stay in the normal order of the webpage. If we use "top", "left", "right", or "bottom", nothing will happen.
.box{
position: static;
}
2. Relative Position
"relative" moves an element from its original position. The original space is still kept, so other elements do not move into that space.
.box{
position: relative;
top: 20px;
left: 30px;
}
<div class="box">Hello</div>
In this example, the box moves 20px down and 30px to the right, but its original space is still reserved.
3. Absolute Position
"absolute" removes the element from the normal page flow. It is placed relative to the nearest parent that has "position: relative", "absolute", "fixed", or "sticky".
<div class="container">
<div class="box">Hello</div>
</div>
.container{
position: relative;
width: 300px;
height: 200px;
border: 2px solid black;
}
.box{
position: absolute;
top: 20px;
right: 20px;
}
Here, the box appears 20px from the top and 20px from the right inside the container.
4. Fixed Position
A "fixed" element is always placed relative to the browser window. Even if we scroll the page, it stays in the same place.
.header{
position: fixed;
top: 0;
width: 100%;
}
This is commonly used for navigation bars or floating buttons.
5. Sticky Position
"sticky" works like "relative" at first. When we scroll and the element reaches the value given in "top", it sticks there until its parent ends.
.navbar{
position: sticky;
top: 0;
}
This is useful for section headings or navigation bars that should stay visible while scrolling.

Top comments (0)