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

实现文本框叠加透明图片及响应式布局的HTML/CSS方案问询

实现文本框与图片叠加布局并适配移动端

需要实现以下效果:

  • PC端:单行布局,灰色文本框与图片部分叠加(图片覆盖文本框右侧区域)
  • 移动端:文本框占满整行,图片下移到文本框下方单独一行

原代码未实现叠加效果,且无移动端适配,以下是修正方案:

修改后的HTML代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文本框与图片叠加布局</title>
</head>
<body>
    <div class="container">
        <div class="text-box">
            <p>这里是文本内容,灰色背景的文本框会被图片部分覆盖。</p>
            <p>可以添加更多文本测试布局效果,确保内容不会溢出。</p>
        </div>
        <div class="image-container">
            <img src="https://picsum.photos/600/400" alt="叠加图片">
        </div>
    </div>
</body>
</html>

修改后的CSS代码

body {
    margin: 0;
    font-family: Arial, sans-serif;
    padding: 20px;
    box-sizing: border-box;
}

.container {
    display: flex;
    align-items: stretch;
    gap: 0;
    max-width: 1200px;
    margin: 0 auto;
}

.text-box {
    background-color: #ccc;
    padding: 30px;
    width: 60%;
    box-sizing: border-box;
    z-index: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.image-container {
    width: 50%;
    margin-left: -10%; /* 关键:左移10%实现与文本框的叠加 */
    z-index: 2;
    overflow: hidden;
}

.image-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .container {
        flex-direction: column;
    }
    .text-box {
        width: 100%;
    }
    .image-container {
        width: 100%;
        margin-left: 0;
        margin-top: 20px;
        height: 250px; /* 移动端图片固定高度,可按需调整 */
    }
}

关键改动说明

  • 叠加效果实现:通过给.image-container设置margin-left: -10%,让图片容器向左偏移,刚好覆盖文本框右侧10%的区域(文本框宽度60%+图片容器宽度50%-偏移10%=100%容器宽度)
  • 布局对齐:容器使用align-items: stretch保证文本框与图片高度一致,文本框内部用flex布局实现文本垂直居中
  • 移动端适配:媒体查询中将容器改为垂直排列,重置图片容器的偏移量,让图片单独占一行,同时设置固定高度保证移动端显示效果
  • 细节优化:给body添加内边距避免内容贴边,图片设置display: block消除默认间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:17:08