Skip to main content

CSS Positioning Properties

CSS positioning properties are a cornerstone of web design as they allow you to control where you want to place your HTML elements on the web page. The CSS positioning properties include: static, relative, fixed, absolute, and sticky. In this tutorial, we will discuss each of these properties in detail.

CSS static Positioning

The static positioning is the default value for the position property in CSS. When an element is set to static, it is always positioned according to the normal flow of the page. This means you cannot use top, bottom, left, or right properties to move the element.

p {
position: static;
}

CSS relative Positioning

When an element is set to relative, it is positioned relative to its normal position. This means you can use top, bottom, left, or right properties to move the element from where it would be in the normal flow of the page.

p {
position: relative;
left: 20px;
}

In the above example, the paragraph will move 20 pixels to the right from where it would be in the normal flow of the page.

CSS fixed Positioning

The fixed position property places an element relative to the browser window. This means that even if the page is scrolled, the fixed positioned element will stay in the same place.

p {
position: fixed;
bottom: 0;
right: 0;
}

In the above example, the paragraph will always be positioned at the bottom right corner of the browser window.

CSS absolute Positioning

The absolute position property places an element relative to its nearest positioned ancestor (instead of positioned relative to the viewport like fixed). However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

p {
position: absolute;
top: 80px;
right: 0;
}

In the above example, the paragraph is positioned 80 pixels from the top of its nearest positioned ancestor.

CSS sticky Positioning

The sticky position is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified point, then it is treated as fixed positioned.

p {
position: sticky;
top: 0;
}

In the above example, the paragraph will start in its relative position, and when the viewport is scrolled down and the paragraph reaches the top, it will stick to the top.

In summary, understanding how to use CSS positioning properties is key to being able to design the layout of web pages. Each position value has its special use cases, and knowing when to use which will greatly enhance your ability to control the exact placement of elements on the page. Happy styling!