0

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.

mr.Hritik
  • 577
  • 3
  • 19
  • 1
    Does this answer your question? [Position absolute but relative to parent](https://stackoverflow.com/questions/10487292/position-absolute-but-relative-to-parent) – user16930239 Sep 26 '21 at 19:19
  • @Jabbar Is their any simpler way to do this ? – mr.Hritik Sep 26 '21 at 19:23
  • If I understand the question right, you need just to apply 'position:relative' to the parent div. Then you can position its children absolutely or relatively to it. – Azu Sep 26 '21 at 19:36
  • yes relatively to it's parent div. @Azu – mr.Hritik Sep 26 '21 at 19:37

1 Answers1

2

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/

Lucas David Ferrero
  • 1,630
  • 14
  • 40
  • Thank you for submitting your answer it is very helpful for me. I found one more explaination on this. So can you add it's link in your ans ? – mr.Hritik Sep 26 '21 at 20:01