1

How to make child div absolute for a grand parent div as below structure?

We know that here child div is absolute for parent div because parent is relative div but here is scenario where parent is relative div as along as grand parent also relative div but and now I want to make child div absolute for grand parent div without changing parent div position. here is code sample code

<!-- grand parent div-->
<div style="position:relative">
  <!-- parent div -->
  <div style="position:relative">
    <!-- child div -->
    <div style="position:absolute">

    </div>
  </div>
</div>

Is there any possibility or not?

Sourav Singh
  • 878
  • 1
  • 8
  • 14
  • 1
    Nope! absolute works for its parent `relative` – Awais Dec 03 '19 at 14:06
  • You would need to remove the parent relative - is it needed as changing it to static (or default) won't change it's position within the grandparent? – Pete Dec 03 '19 at 14:09

1 Answers1

3

Make the child fixed and apply a null transform on the grand-parent (if you don't already have a transform applied to it) to make it the containing block of the fixed element. With this you will have the expected result.

.grand {
  border:5px solid;
  padding:50px;
  transform:translate(0);
  margin:50px;
}
.parent {
  height:100px;
  border:5px solid red;
}
.child {
  width:50px;
  height:50px;
  background:green;
  top:0;
  left:0;
}
<!-- grand parent div-->
<div style="position:relative" class="grand">
  <!-- parent div -->
  <div style="position:relative" class="parent">
    <!-- child div -->
    <div style="position:fixed" class="child">

    </div>
  </div>
</div>

It works also with a filter property:

.grand {
  border:5px solid;
  padding:50px;
  filter:opacity(100%);
  margin:50px;
}
.parent {
  height:100px;
  border:5px solid red;
}
.child {
  width:50px;
  height:50px;
  background:green;
  top:0;
  left:0;
}
<!-- grand parent div-->
<div style="position:relative" class="grand">
  <!-- parent div -->
  <div style="position:relative" class="parent">
    <!-- child div -->
    <div style="position:fixed" class="child">

    </div>
  </div>
</div>

Related to understand the trick: CSS-Filter on parent breaks child positioning

Temani Afif
  • 245,468
  • 26
  • 309
  • 415