You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不修改#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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:36:03