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

如何实现div背景图与body同图且仅div区域反色并对齐全屏?

解决方案

要实现welcome div的背景与body完全对齐且仅在div范围内反色,关键是让div的背景基于视口定位,而非自身元素。修改后的CSS如下:

.welcome {
    background-image: url("bg.jpg"); /* 和body使用相同背景图 */
    filter: invert(1);
    background-size: cover;
    background-position: center center; /* 与body的cover默认定位保持一致 */
    background-attachment: fixed; /* 核心:让背景相对于视口固定,而非div自身 */
    background-repeat: no-repeat;
}

原理说明

  • 原代码中background-size: cover是相对于div自身尺寸缩放背景,导致背景与body的全屏背景错位。
  • 添加background-attachment: fixed后,背景会以整个视口为基准进行定位和缩放,与body的cover背景完全匹配,div仅显示自身范围内的背景区域,再通过filter: invert(1)实现局部反色。

补充优化

如果body的背景属性后续可能修改,也可以用inherit继承背景图,减少重复代码:

.welcome {
    background-image: inherit;
    filter: invert(1);
    background-size: cover;
    background-position: center center;
    background-attachment: fixed;
    background-repeat: no-repeat;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:12:42