CSS Position
The CSS Position property allows you to specify how an element is positioned on a web page. There are five possible values for the position property: static, relative, absolute, fixed, and sticky.
static
By default, all elements on a web page have a static position. This means that the element will be displayed in the normal flow of the document. The position of the element will be determined by the layout of the document and any other elements around it.
relative
When you set an element's position to relative, it will be positioned relative to its normal position in the document flow. You can then use the top, right, bottom, and left properties to move the element from its original position.
Example:
.box {
position: relative;
top: 20px;
left: 30px;
}
| Before | After |
|---|---|
| .box | .box |
absolute
When you set an element's position to absolute, it will be positioned relative to its nearest positioned ancestor. If there is no positioned ancestor, it will be positioned relative to the initial containing block (usually the <body> element).
Example:
.container {
position: relative;
}
.abs-box {
position: absolute;
top: 50px;
left: 100px;
}
| .container | .abs-box |
|---|---|
| .container | .abs-box |
fixed
When you set an element's position to fixed, it will be positioned relative to the browser window, regardless of where the element is in the document flow. This means that the element will stay in the same position on the screen, even when the user scrolls the page.
Example:
.fixed-box {
position: fixed;
top: 20px;
right: 20px;
}
| Before | After scroll |
|---|---|
| .fixed-box |
sticky
When you set an element's position to sticky, it will behave like relative positioning until it reaches a specified scroll position, then it will "stick" in place. This can be useful for creating headers or sidebars that stay in view as the user scrolls.
Example:
.sticky-box {
position: sticky;
top: 0;
}
In this example, the .sticky-box element will stick to the top of the viewport when the user scrolls past it.