As you can see their are two boxes, with one parent div and one sub div inside wrapper div. So i want to apply position absolute inside their relative parent div not to body.
/*--CSS--*/
.wrapper{
Height:80vh;
border:1px solid red;
}
.div_1{
Height:70vh;
border:1px solid blue;
margin:20px;
}
.sub_div{
Height:40vh;
border:1px solid green;
margin:20px;
}
.box{
height:100px;
width:100px;
background:orange;
position:absolute; /*Applied position absolute*/
}
.box1{
display:flex;
justify-content:center;
align-items:center;
top:0;
left:0;
}
.box2{
display:flex;
justify-content:center;
align-items:center;
bottom:0;
right:0;
}
<!--HTML-->
<div class="wrapper">
<div class="div_1">
<div class="box box1">
box1
</div>
<div class="sub_div">
<div class="box box2">
box2
</div>
</div>
</div>
</div>
So is their any way to achieve this.
CodePudding user response:
position absolute:
It will position itself according to the closest positioned ancestor.
In your case, you don't have any positioned ancestor, so your absolute elements will position to the viewport.
You have to give your ancestors a position different from static. I suggest using relative
in this case since it respects the flow of the page.
You have to add this in your CSS:
.div_1{
height:70vh;
border:1px solid blue;
margin:20px;
position: relative; // now this element is considered a positioned element.
}
.sub_div{
height:40vh;
border:1px solid green;
margin:20px;
position: relative;
}
You can read more about how position affects your elements at: https://cssreference.io/positioning/