Drupal 10 introduces a novel auto-filling CSS Grid technique, and we're excited to share it.
The key features are:
Observe how the grid responds when compressed by the draggable element to its left.
Ready to implement? Here's the CSS:
.grid-container { /* User-defined values */ --grid-layout-gap: 10px; --grid-column-count: 4; --grid-item--min-width: 100px; /* Calculated values */ --gap-count: calc(var(--grid-column-count) - 1); --total-gap-width: calc(var(--gap-count) * var(--grid-layout-gap)); --grid-item--max-width: calc((100% - var(--total-gap-width)) / var(--grid-column-count)); display: grid; grid-template-columns: repeat(auto-fill, minmax(max(var(--grid-item--min-width), var(--grid-item--max-width)), 1fr)); grid-gap: var(--grid-layout-gap); }
This code leverages modern CSS features: CSS Grid's repeat()
, auto-fill()
, and minmax()
functions, along with max()
and calc()
.
auto-fill()
Explainedauto-fill()
is crucial for dynamically filling rows with columns. For a deeper dive into auto-fill()
versus auto-fit()
, see Sara Soueidan's excellent article and accompanying video.
max()
The max()
function prevents excessive columns. It ensures each grid cell's width doesn't exceed a calculated percentage while maintaining a minimum width. The calculation accounts for grid gaps:
max(calc(25% - <grid-gap-for-one-cell>), 100px)</grid-gap-for-one-cell>
This is achieved using CSS variables:
--gap-count: calc(var(--grid-column-count) - 1); --total-gap-width: calc(var(--gap-count) * var(--grid-layout-gap)); --grid-item--max-width: calc((100% - var(--total-gap-width)) / var(--grid-column-count));
This dynamically calculates the maximum width, considering the number of columns and gaps.
minmax()
minmax()
guarantees that grid cells always stretch to fill the container width. It sets a minimum width and allows expansion to 1fr
(fractional unit) if space permits:
minmax(<grid-item-width>, 1fr)</grid-item-width>
Combining these elements, the final code achieves the desired auto-filling behavior:
--gap-count: calc(var(--grid-column-count) - 1); --total-gap-width: calc(var(--gap-count) * var(--grid-layout-gap)); --grid-item--max-width: calc((100% - var(--total-gap-width)) / var(--grid-column-count)); grid-template-columns: repeat(auto-fill, minmax(max(var(--grid-item--min-width), var(--grid-item--max-width)), 1fr));
This example showcases the advanced capabilities of modern CSS. We've created a complex layout without JavaScript, demonstrating the evolution of CSS.
Thanks to Andy Blum for the suggestion to use auto-fill()
, and to the CSS spec writers and implementers for making this possible.
The above is the detailed content of An Auto-Filling CSS Grid With Max Columns of a Minimum Size. For more information, please follow other related articles on the PHP Chinese website!