Home > Web Front-end > CSS Tutorial > How to Limit the Maximum Number of Columns in CSS Grid Without Media Queries?

How to Limit the Maximum Number of Columns in CSS Grid Without Media Queries?

Barbara Streisand
Release: 2024-11-30 07:23:10
Original
140 people have browsed it

How to Limit the Maximum Number of Columns in CSS Grid Without Media Queries?

CSS Grid: Specifying a Maximum Number of Columns Without Media Queries

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));
Copy after login

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));
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template