CSS Grid provides a powerful approach to layout web elements, but sometimes you may need to specify a maximum number of columns in your grid while still allowing elements to wrap to new rows as the screen width changes.
To achieve this without media queries or JavaScript, consider using the following CSS rule:
grid-template-columns: repeat(auto-fill, minmax(max(width, 100%/N), 1fr));
Here, N represents the maximum number of columns you want to limit your grid to.
The max(width, 100%/N) portion ensures that each column will have a minimum width of either the container's width or 100%/N (whichever is greater). This configuration effectively limits the number of columns to N while allowing elements to wrap to new rows when necessary.
For example:
.grid-container { --n: 4; /* Set the maximum number of columns to 4 */ display: grid; grid-template-columns: repeat(auto-fill, minmax(max(200px, 100%/var(--n)), 1fr)); }
This CSS will create a grid with a maximum of 4 columns, with each column having a minimum width of either 200px or 25% of the container's width.
You can adjust the --n value to change the maximum number of columns as needed.
This solution provides a flexible and customizable approach to creating grids with a limited number of columns while still maintaining responsiveness across different screen sizes.
The above is the detailed content of How to Limit the Maximum Number of Columns in CSS Grid Without Media Queries?. For more information, please follow other related articles on the PHP Chinese website!