How to Position Elements Using CSS
Code Playground is only enabled on larger screen sizes.
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 option, 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.
Try this in the playground, and notice that 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 the user scrolls past a specific scroll threshold, until that, the element behaves like relative.
<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;
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="static">Static</div> <div class="relative">Relative</div> </body> </html>