How to Use the Position Property in CSS

How to Use the Position Property in CSS

CSS has many properties for styling web pages and web apps; one of those properties you may use is the position property. There are 5 different types of positions:

  • Absolute

  • Fixed

  • Relative

  • Sticky

  • Static

In this article, you will learn about all 5 and how they are used when building UIs. At the end, there will be a Codepen showing an example of all the positions being used.

Static

Static is the default position for HTML elements. It goes with the normal flow of the document. It is positioned in the order it appears in HTML and does not respond to any positional offsets(top, left, right, bottom) or adjustments.

There's honestly no need to add the static to elements since this is the default, but below is a code snippet. Literally, nothing happens.

/* with Plain CSS */
element {
    position: static;
}

/* with Tailwind.css */
element {
    @apply static;
}

Absolute

The absolute position allows you to take an element out of the normal flow of the document and position it relative to its nearest positioned ancestor. It's often used for overlays, tooltips, and elements that need to be precisely positioned within a parent element.

element {
    position: absolute;
    top: 20px;
    left: 28px;
}

/* with Tailwind.css */
element {
    @apply absolute top-5 left-7;
}

Relative

Relative does go with the normal flow of the document but also allows for adjusting an element's position from its default position. It's often used for fine-tuning layouts.

In the code snippet below. If you add the following properties to an element, the element will be moved down by 10px and to the left by 5px

/* with Plain CSS*/
element {
    position: relative;
    top: 10px;
    left: -5px;
}

/*with Tailwind.css*/
element {
    @apply relative top-2.5 -left-1.5;
}

Fixed

This position will be within the viewport regardless of where the user scrolls. It's commonly used for navbars and other types of elements that should remain visible while the user scrolls through content.

In the code snippet below, if you apply the following properties to an element, the element will appear in the top right corner of the viewport.

/* with Plain CSS */
element {
    position: fixed;
    top: 0;
    right: 0;
}

/* with Tailwind.css */
element {
    @apply fixed top-0 right-0;
}

Sticky

Sticky is a hybrid of relative and fixed. An element with a sticky position will behave as relative initially but as soon as the user scrolls to a certain position, it will be fixed. You will often see it used for headers or sidebars that stick to the top of the screen as users scroll.

/* with Plain css */
element {
    position: sticky;
    top: 20px;
}

/* with Tailwind.css */
element {
    @apply absolute top-5;
}

Codepen Example

Did you find this article valuable?

Support Karelle Hofler by becoming a sponsor. Any amount is appreciated!