The div
with position: absolute
has the absolute positioning always referring to the div
parent that has relative positioning. If no% of parent% has relative positioning, its positioning will be absolute relative to the body, that is, div
will be 100% of the width of the width: 100%
tag.
.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 remove body
from position: relative
to see what happens.
In this answer I'll give you more details on how absolute placement works.
EDIT
Remember that .relative
is absolute with respect to the first div.absolute
that contains div
that is at any level above in the DOM, not necessarily the his father straight. This means that the position: relative
relation does not necessarily have to 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 div.relative > div.absolute
is relative to .absolute
, ignoring .relative
. If .middle
contained .middle
, position: relative
would be relative to .absolute
. If .middle
is removed from position: relative
, the yellow range will occupy 100% of the window (in this case, where .relative
does not contain .middle
).