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

如何固定div使其不会随页面overflow-y滚动而发生位移

问题原因

你给提示文本用了position: fixed定位,这个属性是相对于浏览器视口定位的,所以页面整体滚动时,提示文本会始终固定在你设置的视口坐标位置,自然会跟着页面一起移动。

解决方法

  1. 首先给父容器.wrapper添加position: relative,让内部元素的绝对定位以当前wrapper为参照
  2. 统一提示文本的样式,把定位改成position: absolute,配合transform: translate(-50%, -50%)实现水平垂直居中,不需要给每个提示单独写不同的top/left值,也不用拆分多个类

修改后的完整代码

CSS部分

.wrapper {
  background-color: grey;
  height: 200px;
  margin-bottom: 10px;
  overflow-y: auto;
  /* 新增相对定位 */
  position: relative;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

th {
  border: 1px solid #dddddd;
  text-align: center;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

/* 统一提示文本样式,不用拆分多个类 */
.no-data-found-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.no-data-found-text {
  font-size: 18px;
}

HTML部分

<div class="wrapper">
  <table>
    <tr>
      <th>First Column</th>
      <th>Second Column</th>
      <th>Third Column</th>
      <th>Fourth Column</th>
      <th>Five Column</th>
    </tr>
  </table>
  <!-- 提示文本统一用相同类名 -->
  <div class="no-data-found-message">
    <span class="no-data-found-text">
      No data found!
    </span>
  </div>
</div>

<div class="wrapper">
  <table>
    <tr>
      <th>First Column</th>
      <th>Second Column</th>
      <th>Third Column</th>
      <th>Fourth Column</th>
      <th>Five Column</th>
    </tr>
  </table>
  <div class="no-data-found-message">
    <span class="no-data-found-text">
      No data found!
    </span>
  </div>
</div>

<div class="wrapper">
  <table>
    <tr>
      <th>First Column</th>
      <th>Second Column</th>
      <th>Third Column</th>
      <th>Fourth Column</th>
      <th>Five Column</th>
    </tr>
  </table>
  <div class="no-data-found-message">
    <span class="no-data-found-text">
      No data found!
    </span>
  </div>
</div>

修改后提示文本会固定在对应wrapper的中心位置,既不会跟着wrapper内部的表格滚动偏移,也不会跟着页面整体滚动移动。

内容的提问来源于stack exchange,提问作者user10114552

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:12:00