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

Position Absolute定位div超出容器问题求助(Bootstrap 5)

解决Bootstrap 5图片遮罩层超出列的问题

问题根源在于两个细节:

  • Bootstrap的.col-4自带左右内边距,你的.slider-img直接复用了这个类,而绝对定位的遮罩层默认基于父元素的内容区域计算宽度
  • 遮罩层.overlay同时设置了width:100%和padding:20px,默认盒模型(content-box)下,元素总宽度是width + padding,必然会超出父容器

给你两种直接有效的解决方法:

方法一:修正遮罩层的盒模型

给.overlay添加box-sizing: border-box,让padding被包含在width:100%的范围内,不会额外增加宽度:

.overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  width: 100%;
  transition: .5s ease;
  opacity: 0;
  font-size: 20px;
  padding: 20px;
  text-align: center;
  /* 新增这行 */
  box-sizing: border-box;
}

方法二:用定位属性替代width设置

既然已经给遮罩层加了left:0和right:0,这两个属性已经能让元素自动占满父容器的宽度,完全不需要再设置width:100%,padding也不会导致超出:

.overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  transition: .5s ease;
  opacity: 0;
  font-size: 20px;
  padding: 20px;
  text-align: center;
  /* 删除width:100% */
}

额外优化建议:给.slider-img加overflow:hidden,避免图片或遮罩层意外超出容器(可选,但更稳妥):

.slider-img {
  position: relative;
  overflow: hidden;
}

修改后的完整代码示例

CSS

.slider-img {
  position: relative;
  overflow: hidden; /* 可选优化 */
}

.img-fluid {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  transition: .5s ease;
  opacity: 0;
  font-size: 20px;
  padding: 20px;
  text-align: center;
  box-sizing: border-box; /* 方法一核心修改 */
}

.slider-img:hover .overlay {
  opacity: 1;
}

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div class="banner">
  <div class="container">
    <div class="row">
      <div class="col-4 slider-img">
        <img src="https://via.placeholder.com/600" class="img-fluid h-100" alt="Latest Hindi Status">
        <div class="overlay">My Name is John</div>
      </div>

      <div class="col-4 slider-img">
        <img src="https://via.placeholder.com/600" class="img-fluid h-100" alt="Latest Hindi Status">
        <div class="overlay">My Name is John</div>
      </div>

      <div class="col-4 slider-img">
        <img src="https://via.placeholder.com/600" class="img-fluid h-100" alt="Latest Hindi Status">
        <div class="overlay">My Name is John</div>
      </div>
    </div>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 19:05:21