Skip to main content

Command Palette

Search for a command to run...

CSS Positions Properties Explained

Updated
2 min read
CSS Positions Properties Explained
J

I am a tech lover and frontend developer specializing in creating scalable, user-friendly, and modern websites/web.

My goal is to help users have a smooth and seamless experience on the web.

in this article we would explain some of the basic CSS positions properties.

Hello everyone, in this article I will discuss on different position properties in CSS, we will see the use cases, and some examples of position properties in CSS.

What is CSS Position Property?

The position CSS property simply sets the position of an element in a document.

There are different types of position properties in css:

  • static

  • relative

  • fixed

  • absolute

  • sticky

Let's explain the function of each property

Static

By default the position of elements on web pages are static, which means they are not affected by the top, bottom, left, and right properties of the web page. They remained positioned where they are.

body{
    position: static;
}

Relative

This is similar to the static position, but with position relative, you can change the element's top, bottom, left, and right positions.

Here's an example of how the code would look like:

.container{
    position: relative;
    top: 20px;
    left: 20px;
}

Fixed

The element has a fixed position, which means it doesn't move an inch from the it's current position. Even while scrolling through the webpage it doesn't change it's position!

Here's an example of how the code would look like:

p{
    position: fixed;
}

Absolute

This is similar to the fixed position we talked about earlier, except this sets the element's absolute position to be relative to it's parent element.

Here's a good example of what we mean

.parent-element{
    position: relative;
    width: 600px;
    height: 600px;
}
.element{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 300px;
    background-color: pink;
}

This sets an absolute position to the .element inside of it's parent-element. It simply means, the positions we set for the .element would not go outside of the parent's element, it stays within the basis of the parent element.

Sticky

An element with sticky position is positioned based on the user's scroll position. It toggles between relative and fixed, depending on the scroll position of the user.

p{
    position: sticky;
    top: 0;
}

Basically what this does is; it sticks the p element to the top once the user starts scrolling.

I hope this article gave you a better understanding of CSS position properties. Thanks for reading.

N

Clean and nice article

1
J
Jahkamso2y ago

Thank you :)