auto-fit: This keyword automatically adjusts the number of grid tracks based on the available space and the content within the grid. It’s ideal for creating flexible layouts that adapt to different screen sizes.
auto-fill: Similar to auto-fit, but it fills the available space with the specified number of tracks, even if it means creating empty tracks.
Basic Usage
CSS
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* Auto-fit based on minimum width */
}
In this example, the grid will automatically adjust the number of columns to fit the available space, ensuring that each column is at least 200px wide.
Additional Considerations
- grid-template-rows: You can use auto-fit or auto-fill for rows as well.
- minmax() function: The minmax() function defines a minimum and maximum size for grid tracks.
- fr units: Use fr units to create flexible grid tracks that distribute available space proportionally.
Example with auto-fill
CSS
.container {
display: grid;
grid-template-columns: repeat(auto-fill, 200px); /* Fixed width */
}
In this example, the grid will always have a minimum of 200px-wide columns, and additional columns will be added if there’s enough space.
Practical Use Cases
- Dynamic content: When the amount of content within the grid varies, auto-fit or auto-fill can help maintain a responsive layout.
- Card-based layouts: For layouts with cards or items of equal width, auto-fit can create a flexible grid.
- Fluid layouts: Combine auto-fit or auto-fill with media queries to create layouts that adapt to different screen sizes.
Best Practices
- Test on various devices: Ensure your grid layout works as expected on different screen sizes and orientations.
- Consider performance: While auto-fit and auto-fill can be efficient, excessive grid tracks might impact performance.
- Use meaningful class names: Make your code more readable by using descriptive class names.
By effectively using auto-fit and auto-fill, you can create dynamic and responsive grid layouts that adapt to different screen sizes and content changes.