Home >Web Front-end >CSS Tutorial >CSS Grid: How to Limit the Maximum Number of Columns Responsively?
CSS Grid: Maintaining a Maximum Number of Columns Without Media Queries
Question:
Is it feasible to define a CSS grid with a maximum number of columns while allowing elements to automatically wrap onto new rows as the screen width changes?
Solution:
Using CSS Grid, you can limit the number of columns through the repeat(auto-fill, minmax(max(width, 100%/N), 1fr)) syntax. Here, N represents the desired maximum number of columns. As the width of the grid container increases, the 100%/N part of the calculation ensures that the width per column never exceeds this limit.
Example:
Consider the following code snippet:
.grid-container { --n: 4; /* The maximum number of columns */ display: grid; grid-template-columns: repeat(auto-fill, minmax(max(200px, 100%/var(--n)), 1fr)); } .grid-item { background: tomato; padding: 5px; height: 50px; margin: 10px; line-height: 50px; color: white; font-weight: bold; font-size: 2em; text-align: center; box-sizing: border-box; }
In this example, the --n custom property is set to 4, defining a maximum of 4 columns. As the container's width changes, items will wrap onto new rows automatically while maintaining the specified column limit.
This solution provides a flexible and responsive grid layout without relying on media queries or JavaScript.
The above is the detailed content of CSS Grid: How to Limit the Maximum Number of Columns Responsively?. For more information, please follow other related articles on the PHP Chinese website!