LogRocket Blog

A guide to the CSS grid-template-columns property

thumbnail

CSS grid-template-columns Property

The grid-template-columns property in CSS defines the number and size of columns in a grid layout. It is used to create grid layouts with a specified number of columns.

Understanding Values

  1. auto: Automatically sets column size based on content and available space. Creates implicit columns if needed.

  2. min-content: Columns are sized to fit the smallest content in the column.

  3. max-content: Columns are sized to fit the largest content in the column.

  4. minmax(min, max): Column size is constrained between a minimum and maximum value.

  5. fit-content(): Adjusts columns to fit its content but won’t exceed the specified size.

  6. <length> / <percentage> / <fraction> / <auto> / ...: Sets the column size using specific length, percentage, fraction, or auto values.

  7. inherit: The column inherits sizing from the parent grid container.

  8. initial: Resets the property to its default behavior.

  9. unset: Inherits grid-template-columns from the parent element.

Global Values

  • inherit: Inherits from the parent element.

  • initial: Resets to default value.

  • unset: Inherits from parent or default value.

Common Issues with Percentage Values

Percentage values can cause overflow in grid layouts when not accounting for gaps. Make sure to subtract gap sizes from the available space to prevent overflow.

Implicit Values

  • auto-fill: Creates a pattern of columns that fit the content and available space.

  • auto-fit: Similar to auto-fill but ensures no empty columns.

Conclusion

Understanding the grid-template-columns property in CSS allows for creating flexible and responsive grid layouts. By utilizing different values, developers can control the size and layout of columns within a grid container effectively.