"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > CSS Grid: How to Set a Maximum Column Count Without Media Queries?

CSS Grid: How to Set a Maximum Column Count Without Media Queries?

2025-03-05에 게시되었습니다
검색:118

CSS Grid: How to Set a Maximum Column Count Without Media Queries?

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:

  1. Create a grid container with the display: grid property.
  2. Set the grid-template-columns property using the repeat() function with auto-fit as the repeat type.
  3. Within auto-fit, use minmax(max(width, 100%/N), 1fr) to specify the column behavior.

Explanation:

  • max(width, 100%/N) ensures that the column width will be either the maximum width or a fraction (100%/N) of the container width.
  • 1fr sets the default column width to be 1 fraction of the remaining space.

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:

<div>

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.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3