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

CSS悬停显示文本时z-index引发div移位问题求助

解决悬停显示完整文本时下方元素移位问题

当悬停第一个div时,white-space: normal会自动撑开元素高度,导致后续div被挤下移;同时默认静态定位的元素无法通过z-index实现层级覆盖。以下是可行的解决方法:

方案:相对定位+绝对定位脱离文档流

通过将文本容器设为绝对定位,既保留原div的固定高度,又让完整文本覆盖在下方元素上方:

修改后的代码

HTML
<html>
<body>
  <div class="container">
    <div><span>1) This is the full title that I want to be revealed. That is super duper long and totally will overlap the next div.</span></div>
    <div><span>2) This is the full title that I want to be revealed. That is super duper long and totally will overlap the next div.</span></div>
    <div><span>3) This is the full title that I want to be revealed. That is super duper long and totally will overlap the next div.</span></div>
  </div>
</body>
</html>
CSS
.container {
  max-width: 100px;
  margin: 0 auto;
}
.container div {
  position: relative; /* 为内部绝对定位元素提供基准 */
  height: 80px;
  background-color: grey;
  overflow: hidden;
}
.container div > span {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.container div:hover > span {
  position: absolute; /* 脱离文档流,不改变原div高度 */
  top: 0;
  left: 0;
  background-color: grey; /* 覆盖下方元素的背景 */
  z-index: 2; /* 提高层级,确保文本在最上层 */
  white-space: normal;
  width: auto;
  max-width: 300px; /* 可选:限制最大宽度实现文本换行 */
}

原理说明

  1. 外层div设置position: relative,让内部绝对定位的span以它为参考坐标。
  2. hover时span变为绝对定位,脱离正常文档流,因此外层div高度保持80px不变,后续div不会移位。
  3. 通过z-index和背景色,让悬停显示的完整文本覆盖在下方元素上方。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:25:16