The position: absolute value is used to place an HTML element at a specific location within its containing element or the web page. An absolutely positioned element is removed from the normal document flow.
In this chapter, you will learn what position: absolute is, how it works, its syntax, and how to position elements using the top, right, bottom, and left properties.
The position: absolute property is used to position an element at an exact location on a web page. When an element is assigned position: absolute, it is removed from the normal document flow and no longer occupies its original space in the layout.
An absolutely positioned element is placed relative to its nearest positioned ancestor. If none of its parent elements has a position value of relative, absolute, fixed, or sticky, the element is positioned relative to the initial containing block (the web page).
selector {
position: absolute;
top: value;
right: value;
bottom: value;
left: value;
}
The following syntax is used to apply absolute positioning.
In this syntax:
The top, right, bottom, and left properties are optional. You can use one or more of these properties depending on where you want to position the element.
An absolutely positioned element is usually placed relative to its nearest positioned parent. Therefore, the parent element is commonly assigned position: relative so that the child element can be positioned inside it.
.container {
position: relative;
}
.box {
position: absolute;
top: 50px;
left: 100px;
}
Explanation
In this example:
The position of an absolutely positioned element can be controlled using one or more offset properties. These properties specify the distance between the element and the corresponding edge of its containing element.
.box {
position: absolute;
top: 20px;
right: 30px;
}
Explanation
In this example:
Similarly, the bottom and left properties can be used to position an element relative to the bottom and left edges.
If no positioned parent element exists, the browser positions the element relative to the web page. In this case, the top, right, bottom, and left properties are measured from the edges of the browser window or the initial containing block.
.box {
position: absolute;
top: 100px;
left: 50px;
}
Explanation
Since no parent element has a positioning property, the browser places the element 100 pixels from the top and 50 pixels from the left side of the web page.
Because absolutely positioned elements are removed from the normal document flow, they can overlap other elements on the page. The z-index property is commonly used to control the stacking order of overlapping elements.
.box1 {
position: absolute;
left: 20px;
top: 20px;
z-index: 2;
}
.box2 {
position: absolute;
left: 40px;
top: 40px;
z-index: 1;
}
Explanation
In this example, both elements overlap each other. Since .box1 has a higher z-index value than .box2, it is displayed in front of .box2.
We request you to subscribe our newsletter for upcoming updates.