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

CSS Grid+Flex实现info-box部分覆盖图片的方案咨询

实现info-box覆盖图片上方的解决方案

问题背景

我正在使用CSS Grid和Flex布局,想要让info-box部分覆盖在图片上方,而不是在图片正下方。试过把图片和info-box放在同一个容器,还给info-container设置了Grid布局,试图上移info-box实现覆盖,但没成功,求可行方案。

实现方案

要实现覆盖效果,核心是让info-box和图片处于同一网格区域,通过负边距调整位置并保证层级。直接修改现有CSS即可,具体代码如下:

修改后的CSS代码

.info-container {
  display: grid;
  grid-template-columns: 1fr minmax(0, 70ch) 1fr;
  column-gap: 1rem;
  >* {
    grid-column: 2;
  }
}

.info-container figure {
  margin: 0; /* 清除figure默认边距 */
}

.info-container img {
  max-block-size: 300px;
  inline-size: 100%;
  object-fit: contain;
  display: block; /* 清除图片下方空白 */
}

.wrapper {
  /* 移除原有的无效网格设置 */
  margin-top: 0;
}

.info-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #1e1e1e;
  padding: 1.5rem 2rem;
  border-radius: 12px;
  color: #fff;
  flex-wrap: wrap;
  /* 关键:负边距上移,z-index保证层级 */
  margin-top: -80px;
  z-index: 1;
  position: relative; /* 让z-index生效 */
}

.info-item {
  text-align: center;
  flex: 1;
  margin: 0.5rem 0;
}

.info-item h4 {
  font-size: 1rem;
  margin: 0;
  padding: 0;
  line-height: 1.2;
  color: #ccc;
}

.info-item p {
  font-size: 0.875rem;
  margin: 0;
}

.live-preview .btn {
  background-color: #f7b500;
  color: #000;
  padding: 0.75rem 1.5rem;
  border-radius: 24px;
  text-decoration: none;
  font-weight: bold;
  display: inline-block;
  margin: 0 auto;
}

.live-preview .btn:hover {
  background-color: #e0a400;
}

@media (max-width: 768px) {
  .info-box {
    flex-direction: column;
    text-align: center;
    /* 移动端调整负边距,避免覆盖过多 */
    margin-top: -60px;
  }
  .info-item {
    margin-bottom: 1rem;
  }
  .live-preview {
    margin-top: 1rem;
  }
}

对应的HTML代码(无需修改)

<div class="info-container">
  <figure>
    <img src="./src/assets/images/case-study-photo2.jpg" alt="" />
  </figure>
  <div class="wrapper">
    <div class="info-box">
      <div class="info-item">
        <h4>Case Name</h4>
        <p>Taxes & Efficiency</p>
      </div>
      <div class="info-item">
        <h4>Category</h4>
        <p>Business</p>
      </div>
      <div class="info-item">
        <h4>Date</h4>
        <p>27th September 2022</p>
      </div>
      <div class="info-item live-preview">
        <a href="#" class="btn">Live Preview</a>
      </div>
    </div>
  </div>
</div>

关键修改说明

  1. 简化网格结构:移除了.wrapper中grid-template-rows: 0这类无效设置,让.info-container的网格布局只负责居中对齐,不需要额外行定义。
  2. 负边距实现覆盖:给.info-box添加margin-top: -80px(可根据设计需求调整数值),让它向上移动覆盖在图片底部区域;同时设置position: relative和z-index: 1,确保info-box层级高于图片。
  3. 清除默认样式:移除figure的默认边距和图片下方的空白,避免布局偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:35:24