Difference between relative , absolute and fixed position in CSS
CSS positioning is a fundamental concept in web design and development. It allows us to control the layout of elements on a webpage. This article will tell you the differences between relative, absolute, and fixed positioning in CSS.
1. Relative Positioning
Relative Position: Relative positioning is a CSS technique that allows an element to be adjusted from its normal position. The syntax for relative positioning is position: relative;
. When you set the top
, right
, bottom
, and left
properties of an element with relative positioning, it moves from its original location. However, it’s important to note that other elements on the page will not fill the gap left by the moved element.
Syntax:
position: relative;
2. Absolute Positioning
Absolute Position is another CSS technique that adjusts an element’s position relative to its parent. If no parent element is present, the document body is used as the parent. The syntax for absolute positioning is position: absolute;
.
position: absolute;
3. Fixed Positioning
Fixed Position is a CSS technique that keeps an element in the same place even when the page is scrolled. The syntax for fixed positioning is position: fixed;
. To position the element, we use top
, right
, bottom
, and left
properties.
Syntax:
position: fixed;
Different Examples of Position Relative, Absolute and Fixed
The below example illustrates the differences between Relative Position and Absolute Position.
1. Relative Position:
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
left: 50px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h1>position: relative;</h1>
<div class="relative">
This element has position:relative;
</div>
</body>
</html>
Output:
2. Absolute Position:
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}
div.absolute {
position: absolute;
top: 80px;
right: 80px;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h1>position: absolute;</h1>
<div class="relative">
This element has position: relative;
<div class="absolute">
This element has position: absolute;
</div>
</div>
</body>
</html>
Output:
3. Fixed Position:
<!DOCTYPE html>
<html>
<head>
<style>
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}
div.absolute {
position: absolute;
top: 150px;
right: 80;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h1>position: absolute;</h1>
<h2>position: fixed;</h2>
<div class="absolute">
This element has position: absolute;
</div>
</body>
</html>
Output: