Position Elements in CSS : Easy to understand
Table of contents
No headings in the article.
Element Position itself says "placing element using properties like left, right, top, bottom.... Simple!!!"
In CSS there are simple three properties which helps to position elements.
/* We are mainly learn this three types of position */
position : absolute
position : relative
position : fixed
Lets learn position properties with example.
Consider a person having own parking area in the parking yard of building. What he suppose to do is parking his car only in his parking area.
This is how absolute works.
Now lets consider a person don't having his own parking area in his building. What he can do is he will starting cheating. He will park anywhere freedomly on the parking yard without any permission. He can use parking yard entirely.
This is how relative works.
Lets see how it works on CSS.
Look at this HTML screen
<div class="yard">
<div class="parking pink">Own Parking Area
<div class="car orange">Car</div>
</div>
</div>
div with class "yard" has its child div with class "parking pink" and also div with class "parking pink" has its child div with class "car orange".
Now look at to CSS
/* Design to understand position in better way */
<style>
body{
background-color: #b1ff9c;
}
.pink{
margin: 55px;
padding: 20px;
background-color: #fcd3d3;
font-family: 'Poppins',serif;
}
.orange{
background-color: #ffc444;
margin-bottom: 5px;
margin-right: 80%;
padding: 10px;
font-family: 'Poppins',serif;
}
</style>
See how it look like....
Now lets play with position.
Put position : relative to class "parking" & class "car".
.parking{
position: relative;
}
.car{
position: relative;
top: 0;
left: 0;
}
and see the change...
Nothing is happen right!!!
Now change the position of class "car" to absolute
.parking{
position: relative;
}
.car{
position: absolute;
top: 0;
left: 0;
}
See the magic....
Lets learn it simply....
relative means its own position & absolute means its parent's position.
What we do is we put parking position as relative. It means element "Own parking area" will not follow his parent's position. It will fixed on its own position.
But for car we put position as absolute. So it means element "Car" use it's parent position to move according. Like when we add top : 0 & left : 0, Car was took its parent position means its Own parking area top left corner position rather taking Parking Yard corner position which is mention in light green color.
Now Let remove the position of class "parking"
/* .parking{
position: relative;
} */
.car{
position: absolute;
top: 0;
left: 0;
}
See the output
Now car will not use his parent position. It used his grand parent position.
Simple is it !!!!
Recap - 1. Relative means own position 2. Absolute means parents position