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

为何CSS Grid布局的div在大视口下无法居中?

Fix: Centering Your Grid Items on Large Viewports

Got it, let's tackle this issue. The problem here is that your grid layout behaves differently on large desktop screens because of two key oversights in your current CSS:

What's Causing the Misalignment?

  1. inline-grid vs. block grid: Using display: inline-grid makes your .inner-tile container act like an inline element, even with width: 100% set. This introduces subtle alignment quirks that only show up when the viewport has extra space to spare.
  2. Missing grid-level alignment: You're using justify-items: center (which centers each event inside its individual grid cell), but you haven't told the grid itself how to position its columns within the container. By default, justify-content is set to start, so columns stick to the left edge when there's unused horizontal space in large viewports.

The Fixed CSS

Here's the adjusted code to get your events centered properly across all viewports:

.inner-tile { 
  display: grid; /* Switched from inline-grid to block grid */
  grid-gap: 5px; 
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); 
  grid-template-rows: 1fr; 
  justify-items: center; /* Keeps individual events centered in their cells */
  justify-content: center; /* Centers the entire grid track within the container */
  width: 100%; 
  height: auto; 
  font-size: 18px; 
  padding-bottom: 10px; 
} 
.event { 
  border: 1px solid grey; 
  border-radius: 4px; 
  min-width: 240px; 
  min-height: 270px; 
  width: 90%; 
  height: auto; 
}

Why This Works

  • Switching to display: grid ensures the container acts as a block-level element, taking full width of its parent without inline-element oddities.
  • Adding justify-content: center tells the grid to split any extra horizontal space equally on both sides of the columns, pushing your event cards to the center of the container instead of left-aligning them.
  • justify-items: center still keeps each event card centered inside its grid cell, which pairs perfectly with your width:90% on .event to maintain that clean inner padding.

Quick Note on iPad Behavior

Your original code worked on iPad because the viewport width is just tight enough to fit your columns without extra space—so there was no room for the left-alignment issue to reveal itself. On larger screens, that unused space exposed the missing justify-content setting.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:12:43