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

如何让容器背景图仅显示在屏幕左右两侧各20%区域?

实现容器左右边缘各20%区域显示背景图

你可以通过以下两种方法实现需求:

方法1:使用多背景图定位

直接利用CSS多背景图特性,将同一张背景图分别定位在容器的左右两侧,各占20%宽度:

.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  min-height: calc(100vh - 20px); /* 确保容器铺满屏幕高度(减去顶部20px外边距) */
  background-image: url("https://via.placeholder.com/800"), url("https://via.placeholder.com/800");
  background-repeat: no-repeat;
  background-size: 20% 100%; /* 每个背景图宽度20%、高度100% */
  background-position: left top, right top; /* 分别定位到左侧和右侧 */
}
<div class="container">
  <!-- 容器内的内容 -->
</div>

方法2:使用伪元素实现(更灵活)

通过::before和::after伪元素创建左右两个背景区块,避免重复引用背景图,还能单独调整左右背景的样式:

.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  min-height: calc(100vh - 20px);
  position: relative; /* 为伪元素提供定位基准 */
  overflow: hidden; /* 防止伪元素超出容器范围 */
}

.container::before,
.container::after {
  content: "";
  position: absolute;
  top: 0;
  bottom: 0;
  width: 20%; /* 宽度占屏幕的20% */
  background-image: url("https://via.placeholder.com/800");
  background-repeat: no-repeat;
  background-size: cover;
}

.container::before {
  left: 0;
  background-position: left center; /* 对齐背景图左侧 */
}

.container::after {
  right: 0;
  background-position: right center; /* 对齐背景图右侧 */
}
<div class="container">
  <!-- 容器内的内容会显示在中间区域,不受背景伪元素遮挡 -->
</div>

补充说明

  • 如果容器高度由内部内容决定,可以去掉min-height属性;如果需要容器始终铺满屏幕高度,则保留该属性。
  • 方法2的伪元素不会干扰容器内的内容布局,适合中间区域需要放置其他元素的场景。

内容的提问来源于stack exchange,提问作者Yafaa Ben Tili

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:59:54