Stevanicus Stevanicus - 1 year ago 167
CSS Question

Keep element position fixed to parent using transform on scroll

I understand it's possible to

position:fixed
a child element relative to it's parent using
transform
. When scrolling the document, is it possible to keep the fixed child's position relative to it's parent, rather than the document?

Demo
https://jsfiddle.net/ds0vbtbt/3/

Update: Above is a simiplied version of my problem.
position:absolute
: is not the solution I'm looking for.

Update:
Doesn't seem possible without JS once the initial transform is performed

Answer Source

Yeah you can do that with position absolute, provided the containing element is set to relative. You don't need the transform property at all.

.test {
  width: 400px;
  height: 400px;
  border: 1px solid;
  position: relative;
}

.box {
  margin-top: 20px;
  width: 300px;
  height: 100px;
  border: 1px solid red;
  position: absolute;
}

Updated fiddle: https://jsfiddle.net/ds0vbtbt/1/

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Update: position: fixed is always going to relative to the view-port - so if you change the window size it will be updated, but when scrolling it wont be. That said, Elements with transforms act as a containing block for fixed position descendants, so position:fixed under something with a transform no longer has fixed behavior. They do work when applied to the same element; the element will be positioned as fixed, and then transformed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download