Menu Close

How to add fixed position but relative to container with CSS?

To add fixed position but relative to container with CSS, we set the contain property of the parent.

For instance, we write

<div class="parent">
  <div class="child"></div>
</div>

to add nested divs.

Then we write

.parent {
  contain: content;
}

.child {
  position: fixed;
  top: 0;
  left: 0;
}

to set contain to content on the parent and set position to fixed on the child to make the child stay fixed in the parent.

Posted in CSS