Position property in CSS – absolute
CSS Position Property – Absolute
In CSS, the position property is used to control how an element is positioned. Position: absolute is a commonly used positioning property. It allows an element to be positioned relative to its nearest positioned parent element, or relative to the top of the document.
Syntax
position: absolute;
How it works
When the position property is set to absolute, an element is removed from the normal document flow and no longer affects the layout of surrounding elements. This allows us to precisely control the element’s position using the top, bottom, left, and right properties.
When using position: absolute, elements are positioned relative to their nearest positioned parent element. If there is no positioned parent element, the element is positioned relative to the top of the document.
Usage examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Absolute Position Demo</title>
<style>
.container {
position: relative;
width: 400px;
height: 400px;
border: 1px solid #ccc;
}
.box {
position: absolute;
top: 50px;
left: 100px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div> </div>
</body>
</html>
In the example above, we create a container element, .container, and an absolutely positioned box element, .box. The container element’s position property is set to relative, meaning the .box element is positioned relative to the .container. The .box element’s position property is set to absolute, and its top and left properties are set to 50px and 100px, respectively. This offsets the .box element 50px down and 100px to the right relative to the .container.
Running Results
Open the example code above in a browser and you’ll see a red square box positioned 50px down and 100px to the right within the gray container.
Using position: absolute allows for more precise control over element positioning, making layouts more flexible and diverse. However, it’s important to note that overuse of absolute positioning can lead to confusing layouts, so use it with caution.