Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
CSS position: relative;
The CSS position: relative property allows you to position an element relative to its normal position in the document flow. The element maintains its original space in the layout, but you can offset it using the top, right, bottom, and left properties.
Syntax
selector {
position: relative;
top: value;
right: value;
bottom: value;
left: value;
}
Key Characteristics
When an element has position: relative −
- It remains in the normal document flow
- Other elements are positioned as if the relatively positioned element is still in its original location
- The element can be moved from its normal position using offset properties
- It creates a new positioning context for absolutely positioned child elements
Example: Basic Relative Positioning
The following example demonstrates how position: relative moves an element from its normal position −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
background-color: #f0f0f0;
padding: 20px;
margin: 10px 0;
}
.box {
width: 150px;
height: 80px;
background-color: #4CAF50;
color: white;
text-align: center;
line-height: 80px;
margin: 10px;
border: 2px solid #333;
}
.relative-box {
position: relative;
left: 30px;
top: 15px;
background-color: #2196F3;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Normal Box 1</div>
<div class="box relative-box">Relative Box</div>
<div class="box">Normal Box 2</div>
</div>
</body>
</html>
Three boxes appear in a gray container. The middle blue box is offset 30px to the right and 15px down from its normal position, while the green boxes maintain their original spacing as if the blue box hadn't moved.
Example: Creating a Positioning Context
Relatively positioned elements serve as positioning contexts for their absolutely positioned children −
<!DOCTYPE html>
<html>
<head>
<style>
.parent {
position: relative;
width: 250px;
height: 150px;
background-color: #e0e0e0;
border: 2px solid #333;
margin: 20px;
}
.child {
position: absolute;
top: 10px;
right: 10px;
width: 80px;
height: 40px;
background-color: #FF5722;
color: white;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div class="parent">
Parent (relative)
<div class="child">Child</div>
</div>
</body>
</html>
A gray parent box with a red child element positioned absolutely in the top-right corner (10px from top and right edges) of the parent container.
Conclusion
The position: relative property is essential for fine-tuning element placement while preserving document flow. It's commonly used to create positioning contexts for child elements and to make minor positional adjustments without affecting surrounding elements.
