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

如何用CSS实现带背景透视窗口的白色矩形效果?

实现带背景透出窗口的着陆页

问题分析

你之前的方案用background-attachment: fixed试图固定背景,但蒙版内的背景未根据窗口位置做偏移,导致无法和页面背景对齐;同时固定背景在响应式场景下容易出现适配问题。我们可以通过同步背景定位+精准偏移计算实现完全对齐的蒙版效果,同时保证响应式和图片比例。

解决方案

核心思路:

  • 页面背景与蒙版内背景使用相同的background-size: cover和定位基准
  • 通过计算蒙版相对于页面的位置,用transform偏移蒙版内的背景,让两者完全重合
  • 用相对定位替代固定定位,避免响应式下的错位

修改后的代码

HTML

<div class="page-container">
  <div class="background-image"></div>
  <div class="white-rectangle">
    <div class="content-area">
      <!-- 左侧内容区域 -->
    </div>
    <div class="mask"></div>
  </div>
</div>

CSS

/* 页面容器,作为所有元素的定位基准 */
.page-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

/* 页面全局背景 */
.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('../../public/alabama-hills.jpg');
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
}

/* 白色矩形主体 */
.white-rectangle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  border-radius: 8px; /* 替换为你的$border-radius变量 */
  width: 80%;
  height: 80%;
  display: flex;
  padding: 1rem;
  gap: 1rem;
  box-sizing: border-box; /* 确保padding不占用额外宽高 */
}

/* 左侧内容区域 */
.content-area {
  flex: 1;
  /* 可添加内容样式 */
}

/* 蒙版窗口 */
.mask {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

/* 蒙版内的背景,通过偏移对齐全局背景 */
.mask::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-image: url('../../public/alabama-hills.jpg');
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  /* 关键:让背景中心与蒙版中心对齐,实现完全重合 */
  transform: translate(-50%, -50%);
  transform-origin: center center;
}

关键说明

  1. 定位基准统一:页面容器设为position: relative,所有元素基于它定位,避免固定定位带来的适配问题。
  2. 背景精准对齐:蒙版内的伪元素宽高设为视口大小,通过transform: translate(-50%, -50%)让其中心与蒙版中心对齐,从而和页面背景完全重合,实现“透出”效果。
  3. 响应式适配:白色矩形用百分比宽高,flex布局自动适配不同屏幕,背景用background-size: cover保持图片比例。
  4. 盒模型优化:添加box-sizing: border-box确保padding不会撑开容器,保证布局稳定性。

额外优化建议

  • 若需支持滚动场景,可将page-container的height: 100vh改为min-height: 100vh,同时调整背景定位逻辑。
  • 用CSS变量统一管理背景图片地址,避免重复书写:
    :root {
      --bg-image: url('../../public/alabama-hills.jpg');
    }
    /* 使用时直接调用var(--bg-image) */
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:07:39