Reputation: 7906
I am not much expert in css. I did not give any position and have css like
#myId{
margin-left: 10px;
margin-top: 10px;
}
#myId{
position: relative;
left: 10px;
top: 10px;
}
Both did exactly what i wanted. When should i use relative position exactly. Any advantage or disadvantage over other?
Upvotes: 3
Views: 1445
Reputation: 43557
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>
Upvotes: 6