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

CSS如何修改子元素背景色且保留父元素设置的背景图片

问题原因

你当前将DNA背景图设置在.container父容器的背景层,子元素.col-white设置的不透明白色背景会覆盖父容器对应区域的背景,所以白色列区域的DNA背景图会被遮挡。

解决方法(推荐:伪元素实现全局统一背景图)

这种方案不需要修改子元素样式,所有区域的DNA背景图统一管理,适配性更强:

修改后的CSS代码

body{
  background-color: yellow;
}
.container{
  position: relative;
  background-color: gray;
}
/* 单独把DNA背景图放在独立的伪元素层,层级高于容器背景、低于内容文字 */
.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('https://raw.githubusercontent.com/skoruba/css-bg-img/main/dna%20(1).png');
  background-repeat: repeat-y;
  background-position: 50px 0;
  /* 避免背景图层阻挡页面点击、选中等交互操作 */
  pointer-events: none;
  z-index: 1;
}
/* 子元素内容层级高于背景图层,避免背景图挡住文字 */
.container > * {
  position: relative;
  z-index: 2;
}

.col-6 {
  padding: 20px;
}

.col-white {
  background-color: white;
}

可选方案:子元素多重背景设置

如果不想修改父容器配置,也可以给白色列同时设置白色底色和DNA背景图,保持和父容器的背景定位参数一致即可:

.col-white {
  background: 
    url('https://raw.githubusercontent.com/skoruba/css-bg-img/main/dna%20(1).png') repeat-y 50px 0,
    #fff;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:06:03