0
0
CssDebug / FixBeginner · 4 min read

How to Fix Grid Items Overflowing in CSS Grid Layout

Grid items overflow when their size or content is larger than the grid container or grid tracks. To fix this, use minmax() for flexible track sizes, set overflow properties, and ensure grid container has proper sizing like max-width or width. Also, avoid fixed widths that exceed container size.
🔍

Why This Happens

Grid items overflow when their size or content is bigger than the grid container or the defined grid tracks. This often happens if grid columns or rows have fixed sizes that are too small or if content inside grid items does not shrink or wrap properly.

css
div.container {
  display: grid;
  grid-template-columns: 200px 200px 200px;
  width: 500px;
  border: 1px solid black;
}

div.item {
  background-color: lightblue;
  padding: 10px;
  white-space: nowrap;
}
Output
Three grid items each 200px wide inside a 500px wide container cause the last item to overflow horizontally outside the container.
🔧

The Fix

Change fixed column widths to flexible ones using minmax() or auto to allow grid tracks to adjust. Also, set overflow on grid items or container to handle extra content. Ensure container width matches or exceeds total grid track widths.

css
div.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  width: 100%;
  max-width: 600px;
  border: 1px solid black;
  gap: 10px;
}

div.item {
  background-color: lightblue;
  padding: 10px;
  overflow-wrap: break-word;
  white-space: normal;
}
Output
Three grid items evenly share the container width without overflowing, content wraps inside items, and the container fits all items.
🛡️

Prevention

To avoid overflow in the future, use flexible grid track sizes like fr units or minmax(). Avoid fixed widths that exceed container size. Use overflow-wrap and white-space to control content inside grid items. Test responsiveness by resizing the browser or container.

Use browser DevTools to inspect grid layout and track sizes. Consider setting box-sizing: border-box; globally to include padding and borders in size calculations.

⚠️

Related Errors

Similar issues include:

  • Grid container collapsing: Happens when container has no height and items overflow vertically.
  • Content overflow inside grid items: Fixed by overflow: hidden; or text-overflow: ellipsis;.
  • Unexpected scrollbars: Caused by margins or padding pushing items outside container; fix with box-sizing: border-box;.

Key Takeaways

Use flexible grid track sizes like minmax() or fr units to prevent overflow.
Ensure grid container width can fit all grid tracks combined.
Control content wrapping inside grid items with overflow-wrap and white-space.
Use box-sizing: border-box to include padding and borders in size calculations.
Test layouts responsively and inspect with browser DevTools.