0

Given the following markup:

#containing-box {
  margin: auto;
  width: 300px;
  height: 300px;
  background: green;
  transform: translate3d(0,0,0);
}

#fixed-box {
  position: fixed;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background: red;
}
<div id="containing-box">
  <div id="fixed-box"></div>
</div>

Is there a way to have the #fixed-box be position relative to the viewport rather than the #containing-box without changing the styles of the #containing-box. I'm fine with adding any extra markup inside of the #containing-box I just need to find a way to break out of the #containing-box.

EDIT

I found an answer to my problem. Just swap out the div with a dialog element instead.

const dialog = document.querySelector('dialog');
dialog.showModal();
#containing-box {
  margin: auto;
  width: 300px;
  height: 300px;
  background: green;
  transform: translate3d(0,0,0);
}

dialog {
  position: fixed;
  top: 0;
  left: 0;
  bottom: auto;
  right: auto;
  width: 100px;
  height: 100px;
  background: red;
}
<div id="containing-box">
  <dialog></dialog>
</div>
Blake Plumb
  • 6,779
  • 3
  • 33
  • 54
  • No, because `containing-box` sets `transform` which means it creates a new stacking-context: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context – Dai Oct 19 '21 at 21:40
  • asyncawait I have tried position fixed, but as Dai said it gets positioned relative to the `containing-box` not the viewport. I was hoping for some css solution I am not aware of to be able to override this default browser behavior. – Blake Plumb Oct 19 '21 at 21:50
  • your only solution is to make the element outside, if you cannot then it's dead – Temani Afif Oct 19 '21 at 22:17

1 Answers1

1

I don't know if you'd want to go this route, but you could, if you had to, move it out of the containing box and append it to the body with a line of javascript.

document.body.appendChild(document.querySelector('#fixed-box'));
#containing-box {
  margin: auto;
  width: 300px;
  height: 300px;
  background: green;
  transform: translate3d(0,0,0);
}

#fixed-box {
  position: fixed;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background: red;
}
<div id="containing-box">
  <div id="fixed-box"></div>
</div>
ray
  • 26,557
  • 5
  • 28
  • 27