如何不修改#containing-box样式,使其内部fixed元素相对于视口定位
问题描述
现有样式与结构代码如下:
#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>
需求:不修改#containing-box的样式,允许在其内部添加任意额外标记,实现让#fixed-box相对于视口而非父元素#containing-box定位,突破父元素的定位约束。
解决方案
可将内部需要fixed定位的div元素替换为dialog元素实现该效果,对应实现代码如下:
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>
内容的提问来源于stack exchange,提问作者Blake Plumb
相关产品推荐
相关产品推荐

