Loading course content...
Loading course content...
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 start to get interesting from the relative position.
With the position set to relative, the element will be placed relative to its default position.
The exact relative position 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 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;
}In this example, the bottom: 10px and right: 10px will anchor the box to the bottom right corner of the webpage.
If an element has the absolute position, it will be placed relative 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 box with relative position, and .absolute is a smaller box placed inside .relative.
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.
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>
<div class="sticky">Sticky</div>
<p>Lorem ipsum. . .</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>