How to Position Elements Usng CSS

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.

html
1<div class="static">Static</div>
2<div class="relative">Relative</div>
css
1.static {
2  position: static;
3}
4
5.relative {
6  position: relative;
7  top: 10px;
8  left: 20px;
9}
Open demo in new tab

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.

html
1<div class="fixed">Fixed</div>
css
1.fixed {
2  position: fixed;
3  bottom: 10px;
4  right: 10px;
5}
Open demo in new tab

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.

html
1<div class="relative">
2  Relative
3  <div class="absolute">Absolute</div>
4</div>
css
1.absolute {
2  position: absolute;
3  right: 20px;
4  bottom: 20px;
5}
Open demo in new tab

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.

html
1<p>Lorem ipsum. . .</p>
2
3<p>. . .</p>
4
5<div class="sticky">Sticky</div>
6
7<p>. . .</p>
css
1.sticky {
2  position: sticky;
3  top: 10px;
4
5  border: solid orange 2px;
6  background-color: bisque;
7  width: 100%;
8  height: 100px;
9}
Open demo in new tab