A Complete Guide to CSS position

CSS position is a property that allows you to control the positioning of elements on your web page. There are four values you can use with the position property: static, relative, absolute, and fixed. Here’s a complete guide to each value and how to use them:

position: static;

This is the default value for all elements, and it means that the element will flow in the normal document flow. In other words, the element will be positioned according to its natural position on the page. This value ignores any top, right, bottom, or left properties that are set.

css

/* Use the default static position */
.element {
position: static;
}

position: relative;

This value allows you to position an element relative to its normal position on the page. You can use the top, right, bottom, and left properties to move the element in any direction.

css
/* Move the element 20 pixels down and 10 pixels to the right */
.element {
position: relative;
top: 20px;
left: 10px;
}

position: absolute;

This value allows you to position an element relative to its closest positioned ancestor, or the body element if no positioned ancestor is found. You can use the top, right, bottom, and left properties to position the element.

css
/* Position the element 20 pixels from the top and 10 pixels from the left of its closest positioned ancestor */
.element {
position: absolute;
top: 20px;
left: 10px;
}

position: fixed;

This value is similar to position: absolute, but the element is positioned relative to the browser window rather than its closest positioned ancestor. This means that the element will stay in the same position even if the user scrolls the page.

css
/* Position the element 20 pixels from the top and 10 pixels from the left of the browser window */
.element {
position: fixed;
top: 20px;
left: 10px;
}

Conclusion

CSS position is a powerful property that allows you to control the positioning of elements on your web page. By using the static, relative, absolute, and fixed values, you can position elements in a variety of ways. The top, right, bottom, and left properties allow you to move elements in any direction. With CSS position, you can create complex layouts and designs that are both beautiful and functional.