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

图片遮罩超出范围问题:如何让遮罩仅覆盖图片区域

解决遮罩覆盖顶部菜单栏的问题

问题核心是绝对定位的伪元素缺少相对定位的父容器。你的.bg-overlay::before使用了position: absolute,但.bg-overlay本身未设置position: relative,导致伪元素会相对于页面根节点(body)定位,因此会覆盖顶部的header区域。

只需给.bg-overlay添加position: relative,就能让伪元素的定位范围限制在该section内部,不会超出到header区域:

.bg-overlay {
  position: relative; /* 新增这一行 */
}

.bg-overlay>* {
  position: relative;
}

.bg-overlay::before {
  content: "";
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0;
  right: 0;
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));
}

修改后,遮罩会完全被限制在.bg-overlay所在的图片横幅区域内,无论屏幕尺寸如何变化,都不会覆盖header或超出图片底部。

修改后的完整代码

CSS 代码

header {
  border-bottom: 5px solid coral;
  font-family: Arial;
}

header a {
  display: inline-block;
  text-decoration: none;
  color: inherit;
}

.bg-image {
  background-image: url('https://images.pexels.com/photos/1647120/pexels-photo-1647120.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1');
  background-size: cover;
  background-position: center;
  background-color: blue;
  background-repeat: no-repeat;
}

.vh-80 {
  min-height: 80vh;
}

.banner-text {
  color: white;
  font-size: 3rem;
  text-align: center;
  font-family: Arial;
}

.bg-overlay {
  position: relative; /* 关键新增 */
}

.bg-overlay>* {
  position: relative;
}

.bg-overlay::before {
  content: "";
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0;
  right: 0;
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));
}

HTML 代码

<header class="grid-spaceBetween-middle ">
  <div class="col-2 ">
    <a href="/index.html" class="logo">
      <p>Logo</p>
    </a>
  </div>
  <nav class="col-10">
    <a href="/#.html">About Us</a>
    <a href="/#.html"></a>
    <a href="/#.html">Business Travel</a>
    <a href="/#.html">Be Inspired</a>
    <a href="/#.html">Contact</a>
  </nav>
</header>

<!-- Image banner -->

<section class="grid-spaceAround vh-80 bg-image bg-overlay">
  <div class="col-12-middle banner-text">
    <p>IT'S ALL <strong>GOOD</strong></p>
  </div>
</section>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:45:30