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

如何为Flex布局的div添加底部背景图?解决背景图不显示问题

解决Flex布局中底部背景图不显示的问题

问题核心原因

你通过::after伪元素添加的背景图无法显示,主要是两个关键点没处理:

  • 伪元素默认缺少content属性,浏览器不会渲染这个元素
  • 伪元素默认是inline类型,没有宽高尺寸,即使设置背景图也无法展示

另外要实现目标效果(每个绿色块底部带装饰图),还需要调整定位逻辑让背景图固定在块的底部区域。

修复后的完整代码

CSS 部分

.group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
}

.block {
  flex: 25%;
}

@media only screen and (max-width: 600px) {
  .block {
    flex: 50%;
  }
}

.main, .block {
  display: flex;
  flex-grow: 1;
}

.main {
  padding: 10px;
}

.text {
  flex-grow: 1;
  background-color: green; 
  padding: 10px;
  padding-bottom: 30px; /* 给底部背景图预留空间,避免盖住文本 */
  position: relative; /* 让伪元素基于当前容器定位 */
}

.text::after {
  content: ''; /* 必须添加,伪元素才会被浏览器渲染 */
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30px; /* 对应背景图的高度,可根据实际图调整 */
  background: url("https://i.sstatic.net/Rsk8S.png") no-repeat center bottom / 100% 100%;
}

HTML 部分(无需修改)

<div class="group">
    <div class="block">
        <div class="main">
            <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
        </div>
    </div>

    <div class="block">
        <div class="main">
            <div class="text">Lorem ipsum.</div>
        </div>
    </div>

    <div class="block">
        <div class="main">
            <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
        </div>
    </div>

    <div class="block">
        <div class="main">
            <div class="text">Lorem ipsum dolor sit amet.</div>
        </div>
    </div>
</div>

关键修改说明

  1. 给.text添加position: relative,让伪元素可以基于这个容器进行绝对定位
  2. 给.text::after添加content: '',这是伪元素被渲染的必要条件
  3. 用position: absolute将伪元素固定在.text的底部,设置width:100%让背景图铺满容器宽度
  4. 调整.text的padding-bottom和伪元素的height,确保背景图不会遮挡文本,同时完整展示装饰图
  5. 将背景图地址替换为你提供的裁剪图,并设置background-size: 100% 100%让图铺满伪元素容器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:47