To div
with position: absolute
has the absolute position always referring to div
parent who has relative positioning. If no div
parent has relative positioning, its positioning will be absolute in relation to the body, ie, width: 100%
will be 100% tag width body
.
.relative{
position: relative;
width: 300px;
height: 300px;
background-color: black;
}
.absolute{
position: absolute;
width: 100%;
height: 20px;
background-color: red;
top:50px;
}
<div class="relative">
<div class="absolute">Teste</div>
</div>
Try to withdraw position: relative
of .relative
for you to see what happens.
In that reply give more details on how absolute positioning works.
EDIT
It is worth remembering that div.absolute
is absolute with respect to first div
containing position: relative
which is in whichever level up in the DOM, not necessarily your direct father. That means the relationship div.relative > div.absolute
need not necessarily be true. Other elements may exist in the middle of this hierarchy. To illustrate:
.relative{
position: relative;
background-color: black;
height: 300px;
width: 300px;
}
.middle{
background-color: red;
height: 150px;
width: 150px;
}
.absolute{
background-color: yellow;
height: 75px;
width: 100%;
position: absolute;
}
<div class="relative">
<div class="middle">
<div class="absolute"></div>
</div>
</div>
See that .absolute
is related to .relative
, ignoring .middle
. If .middle
contivesse position: relative
, .absolute
would relate to .middle
. Case position: relative
is withdrawn from .relative
, the yellow band will occupy 100% of the window (in the current case, where .middle
does not contain .relative
).