Case 1
You have inner element that is positioned absolute
and want that element to stick to it's parent. Than you apply position: relative
to parent element. By default absolute element pops out from DOM flow and takes position from closest relative element (html by default)
Case 2
You want to move element but still keep it in DOM flow. Than apply position: relative
and move it with left
/right
/top
/bottom
properties.
Case 3
You want to place one element over another. Static elements does not take effect of z-index
that's why you need to set it's position to relative
, static
or fixed
There may be other use cases
.a {
background-color: #ddd;
left: 50px;
top: 150px;
position: relative;
width: 200px;
height: 200px;
text-align: center;
}
.absolute,
.a div {
position: absolute;
left: 50px;
top: 50px;
width: 100%;
height: 60px;
background-color: rgba(250, 0, 0, .4);
}
<div class="a">
HTML > relative
<div>HTML > relative > absolute</div>
</div>
<div class="absolute">HTML > absolute</div>
.a {
position: relative;
left: -20px;
}
.b {
margin-left: -20px;
}
.wrapper {
border-bottom: 2px solid #454545;
}
<div class="wrapper">
relative moving content
<br/>
<span>some content to overlap</span>
<span class="relative a">some content</span>
<span>some content</span>
</div>
<div class="wrapper">
using margins
<br/>
<span>some content to overlap</span>
<span class="relative b">some content</span>
<span>some content</span>
</div>