At Gorazdo, we have created a solution to the challenge of auto-sizing columns in CSS Grid using auto-fit
or auto-fill
. Adding the min
function to minmax
function ensures more resilient and usable grid layouts that adapt to available space. This flexible solution prevents columns or cards from overflowing if the given container lacks space.
When working with CSS Grid, two popular techniques for auto-sizing columns are `auto-fill` and auto-fit
. While both techniques can be useful, they have potential downsides. For example, auto-fill
can result in uneven column widths when the available space is not evenly divisible by the column width, while auto-fit
can result in extra whitespace when there is more space available than needed for the content.
This solution works if the given value in pixels less than the container width. If not, for example, consider the following value repeat(auto-fit, minmax(400px, 1fr))
; the column will overflow the container on mobile or narrow device screens.
At Gorazdo, we admire solutions that cover potential edge cases.
TL; DR
grid-template-columns: repeat(auto-fit, minmax(min(400px, 100%), 1fr))
To create a more resilient and flexible approach for auto-sizing columns, consider using a combination of minmax
and min
functions. The minmax
function allows you to set a minimum and maximum width for each column, while the min
function ensures that the column width is never less than a certain value. Here's an example:
In this example, we're using auto-fit
to fill any extra available space while still maintaining a consistent minimum width for each column. The minmax
function sets a minimum width of either 400px
or 100%
of the available space, whichever is greater. The 1fr
value ensures that the columns expand to fill any extra available space.
This approach ensures that your grid layout remains flexible and responsive while also preventing columns from becoming too narrow on smaller screens or devices. Additionally, using auto-fit
in conjunction with minmax
and min
allows the columns to adjust to the available space while still maintaining a consistent minimum width.
Auto-sizing columns in CSS Grid can be a challenging task. Still, by combining minmax
and min
functions, you can create a more resilient and flexible approach that works well in a variety of scenarios. This approach ensures that your grid layout remains visually appealing and usable on all devices while also adapting to the available space. Additionally, the min
function ensures that the columns or cards will not overflow if the given container has not enough space. Give it a try in your next project and see how it works for you!
Posted on Sunday, April 23, 2023
Updated 11 months ago
Author