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

如何解决纯色背景左右网格的文字居中与图片适配问题

网页Grid布局问题修复方案

关键修改说明

  • 左侧文本垂直居中:给.text容器添加弹性布局,实现内容在网格项内垂直+水平居中,同时通过margin-bottom控制标题和描述的20px间距
  • 右侧图片适配:给.apu-img容器添加弹性布局居中图片,用object-fit: contain保证图片比例不被拉伸/裁剪,同时让网格容器占满面板高度,避免图片超出边框
  • 修正原代码语法错误:比如h1选择器多余的点、alt属性引号错误、size属性误用为font-size

修改后完整代码

CSS代码

.colored-panel {
    background-color: #6A1A2F;
    padding: 20px;
    height: 460px;
    color: #333;
}

.grid-container {  
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 20px;
    color: white;
    height: 100%; /* 让网格容器占满面板高度 */
}

/* 左侧文本容器:垂直水平居中 */
.text {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.text h1 {
    padding: 10px;
    font-size: 60px;
    margin-bottom: 20px; /* 标题和描述的间距 */
}

.text p {
    margin: 0;
}

/* 右侧图片容器:居中图片并限制尺寸 */
.apu-img {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    overflow: hidden;
}

.apu-image {
    max-height: 100%;
    max-width: 100%;
    object-fit: contain; /* 保持图片比例,完整显示在容器内 */
}

HTML代码

<div class="colored-panel">
    <div class="grid-container">
        <div class="text">
            <h1>Welcome to my website!</h1>
            <p>test</p> 
        </div>
        <div class="apu-img">
            <img class="apu-image" src="pics/apu.jpg" alt="Picture of Apu Siqay">
        </div>
    </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:35:36