Stevanicus Stevanicus - 2 years ago 212
CSS Question

Keep element position fixed to parent using transform on scroll

I understand it's possible to

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


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

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:

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