This post was originally published at thedevspace.io. Everything you need to master web development, all in one place.
The position property controls how you wish to position an element. There are five different position methods available, including static, relative, fixed, absolute, and sticky. static is the default positioning method, meaning the element is not positioned in any special way.
Things get more interesting starting from the relative position.
Relative position
With the position set to relative, the element will be placed relative to its default position. It can be adjusted by setting the left, right, top, or bottom properties.
<div class="static">Static</div>
<div class="relative">Relative</div>
.static {
position: static;
}
.relative {
position: relative;
top: 10px;
left: 20px;
}
Fixed position
fixed position means that the element is positioned relative to the viewport. This method can be useful when you need to create a component, such as a navigation bar, that always stays at the top of the webpage, no matter the user's scrolling position. Or when you need a pop-up window that stays at the bottom right corner.
<div class="fixed">Fixed</div>
.fixed {
position: fixed;
bottom: 10px;
right: 10px;
}
Together, the right and bottom properties will anchor the <div> element to the bottom right corner of the webpage.
Absolute position
If an element has the absolute position, it will be placed according to its closest positioned ancestor, which should have a positioning method other than static.
<div class="relative">
Relative
<div class="absolute">Absolute</div>
</div>
.absolute {
position: absolute;
right: 20px;
bottom: 20px;
}
In this example, .relative is a 500x500px box with relative position, and .absolute is a smaller box placed inside .relative. As you can see from the demonstration, the .absolute box is positioned relative to the .relative box instead of the viewport.
If the absolute element does not have a positioned ancestor, it will be positioned relative to the viewport, making it behave like a fixed element.
Sticky position
The sticky option is similar to fixed, except the element will be fixed only when a specific scroll threshold is reached.
<p>Lorem ipsum. . .</p>
<p>. . .</p>
<div class="sticky">Sticky</div>
<p>. . .</p>
.sticky {
position: sticky;
top: 10px;
border: solid orange 2px;
background-color: bisque;
width: 100%;
height: 100px;
}
Read More
If you found this guide helpful, follow us on social media for more tips, tutorials, and updates on web development:
πΉ TheDevSpace | LinkedIn
πΉ TheDevSpace | X
πΉ TheDevSpace | Threads
Let's stay connected! π
Top comments (0)