CSS Grid: Defining a Maximum Number of Columns Without Media Queries
Question:
Can we specify a CSS grid with a maximum number of columns, while allowing elements to dynamically wrap onto new rows as the screen width changes?
Answer:
Yes, using CSS Grid, we can achieve this without the use of JavaScript or media queries. This approach utilizes the concept of auto-fit columns:
Solution:
Explanation:
As a result, when the container width is increased, the columns will expand to fit the available space within the defined maximum number of columns. Elements will automatically wrap to new rows as necessary.
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)); }
Example:
In the following example, a grid container is created with a maximum of 4 columns, and the elements wrap accordingly:
With this approach, we can define a maximum number of columns in a CSS grid, allowing elements to wrap onto new rows as the screen width changes, without the need for media queries.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3