Is it feasible to define a grid with a set maximum number of columns while allowing elements to break onto new rows when the viewport size changes? By default, grids allow columns to expand infinitely, which may lead to undesirable layouts on narrower screens.
To address this, CSS Grid introduces the concept of using max() within the grid-template-columns property. The max() function accepts two parameters: the first representing the maximum width of a single column, and the second ensuring that each column remains responsive within its parent container.
Consider the following code snippet:
.grid-container { --n: 4; /* Maximum number of columns */ display: grid; grid-template-columns: repeat( auto-fill, minmax(max(200px, 100%/var(--n)), 1fr) ); }
Here, --n defines the maximum number of columns. minmax() ensures that each column has a minimum width of 200px, but will not exceed 100%/var(--n). This formula guarantees that as the container width increases, the column width will never surpass 100%/maximum_number_of_columns, preventing the creation of additional columns.
This technique enables you to create grids with a responsive design that adapts to various screen sizes while maintaining the specified maximum column count.
The above is the detailed content of How Can I Set a Maximum Number of Columns in a CSS Grid without Using Media Queries?. For more information, please follow other related articles on the PHP Chinese website!