Home > Web Front-end > CSS Tutorial > How Can I Set a Maximum Number of Columns in a CSS Grid without Using Media Queries?

How Can I Set a Maximum Number of Columns in a CSS Grid without Using Media Queries?

Susan Sarandon
Release: 2024-11-26 09:28:10
Original
817 people have browsed it

How Can I Set a Maximum Number of Columns in a CSS Grid without Using Media Queries?

Maximum Number of Columns in CSS Grid without Media Queries

Defining Grid Maximum Column Count

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.

Achieving a Grid with Maximum Column Count

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.

Implementation

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

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!

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