首页 > 解决方案 > 如何修复相对于可滚动容器的 div?

问题描述

请看这个最小的例子

.container {
  position: relative;
  width: 200px;
  height: 200px;
  border: 3px solid gray;
  overflow: scroll;
}

.box {
  width: 100%;
  height: 800px;
  background: linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(253,187,45,1) 100%);
}

.loading-cover {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
  opacity: 0.5;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <div class="loading-cover">
    Loading
  </div>
  
  <div class="box"></div>
</div>

在此处输入图像描述

我想在滚动时修复白色覆盖。

我试过inset: 0or width: 100%;height:100%;on loading-cover,但没有运气。

position: sticky;在这种情况下也无法使用,因为它粘在窗口视口上,而不是可滚动容器上。

有什么办法可以解决这个问题吗?

标签: css

解决方案


这可能不是解决方案的最短路径,但它确实有效。如果您不需要支持 IE,它可能会支持跨浏览器测试。

这是loading在容器上使用一个应用粘性::before伪元素的类,底部边距为负,以使内容在其下方弹出。有点傻,但这是一个奇怪的情况。我还删除了一些不必要的宽度值并更改overflowoverflow-y,这在您的情况下可能有用,也可能没用。

有了这个,您可以通过向容器添加或删除类来打开和关闭“加载”消息。

.container {
  position: relative;
  width: 200px;
  height: 200px;
  border: 3px solid gray;
  overflow-y: scroll;
}

.box {
  height: 800px;
  background: linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(253,187,45,1) 100%);
}

.container.loading::before {
  position: sticky;
  top: 0;
  height: 200px;
  margin-bottom: -200px;
  background: white;
  opacity: 0.5;
  display: flex;
  align-items: center;
  justify-content: center;
  content: 'Loading';
}
<div class="container loading">

     <div class="box"></div>

</div>


推荐阅读