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

如何用CSS Grid实现图片对齐?网站布局自适应问题求助

问题分析与修复方案

核心问题

  1. 错误将ul和img直接绑定到父级.pm的网格区域,忽略了它们的直接父元素.container,导致布局逻辑混乱
  2. img的max-width:30%限制了图片尺寸,无法和列表按比例拉伸适配
  3. .pm使用inline-grid可能导致容器无法占满可用宽度

修复后的代码

CSS 代码

.pm {
  display: grid; /* 替换inline-grid为grid,确保容器占满可用宽度 */
  max-width: 100%;
  margin: auto;
  grid-template-areas: 
    "title title" 
    "container container" 
    "options options" 
    "paragraph paragraph";
  grid-template-rows: auto 1fr auto auto; /* 用auto替代百分比,自适应内容高度 */
  gap: 1rem; /* 添加间距提升可读性 */
}

.pm h2 {
  grid-area: title;
  text-align: center;
  margin: 0;
}

/* 给container设置内部网格,实现列表和图片同排缩放 */
.pm .container {
  display: grid;
  grid-template-columns: 1fr 1fr; /* 列表和图片各占50%宽度 */
  gap: 1.5rem;
  align-items: start; /* 内容顶部对齐,避免垂直居中导致的布局偏移 */
}

.pm .container ul {
  margin: 0;
  padding-left: 1.5rem;
}

.pm .container img {
  width: 100%; /* 图片占满所在网格列宽度 */
  height: auto; /* 保持图片比例 */
  border-radius: 0.25em;
}

.pm .options {
  grid-area: options;
}

.pm .paragraph {
  grid-area: paragraph;
}

HTML 代码(结构无需修改)

<div class="pm section">
  <h2>Preventative Maintenance:</h2>
  
  <div class="container">
    <ul>
      <li>Calibration of each piece of equipment as required.</li>
      <li>Inspect any switches, controls and/or electrical components.</li>
      <li>Inspect motor brushes and clean the motor fan vents.</li>
      <li>Inspect and tighten hardware.</li>
      <li>Inspect all belts cables and chains.</li>
      <li>Lube all moving components as required.</li>
    </ul>
    <img src="./style/images/circuit.avif">
  </div>
  
  <div class="options">
    <h3>Options:</h3>
    
    <ul>
      <li>Monthly</li>
      <li>Quarterly</li>
      <li>Semi-annual</li>
      <li>Annual</li>
    </ul>
  </div>
  
  <div class="paragraph">
    <p>Any findings will be reported in the invoice, with an option to have any findings quoted for repair, separately.</p>
    
    <p>Any parts needed, per the repair quote, would be ordered and all repairs would be scheduled following arrival of the parts.</p>
  </div>
</div>

关键调整说明

  • 让.container成为.pm网格的整行项目,在.container内部单独设置网格布局,精准控制列表和图片的排列
  • 图片设置width:100%,确保随屏幕尺寸按比例拉伸,填满所在网格列
  • 用auto定义行高,避免固定百分比导致的内容溢出或布局塌陷
  • 添加gap属性,让各区块间有合理间距,提升页面美观度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:45:42