How to Fix Grid Items Overflowing in CSS Grid Layout
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.
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;
}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.
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;
}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;ortext-overflow: ellipsis;. - Unexpected scrollbars: Caused by margins or padding pushing items outside container; fix with
box-sizing: border-box;.