The grid-template-columns
property defines the size and number of columns in a CSS Grid Layout. You specify a space-separated list of values to set the width of each column track.
Example 1: Using Pixels
/* Defines a grid with three columns */
.grid-container {
display: grid;
/* First column is 100px, second is 200px, and third is 150px wide */
grid-template-columns: 100px 200px 150px;
}
Explanation This code creates a grid with three columns of fixed widths. Using pixel values provides precise control over the column sizes, but they are not responsive.
Example 2: Using Percentages
/* Defines a responsive three-column grid */
.grid-container {
display: grid;
/* Columns take up 25%, 50%, and 25% of the container's width respectively */
grid-template-columns: 25% 50% 25%;
}
Explanation This example uses percentages to create a fluid grid layout. The column widths will scale relative to the total width of the grid container.
Example 3: Using Fractional Units (fr)
/* Defines a flexible three-column grid */
.grid-container {
display: grid;
/* The available space is divided into 4 parts; 1fr gets 1 part, 2fr gets 2 */
grid-template-columns: 1fr 2fr 1fr;
}
Explanation The fr
unit represents a fraction of the available space in the grid container. This allows for flexible columns that automatically adjust their size.
Example 4: Using the repeat() function
/* Defines a grid with 4 equal columns */
.grid-container {
display: grid;
/* Creates 4 columns, each taking up 1 fraction of the available space */
grid-template-columns: repeat(4, 1fr);
}
Explanation The repeat()
function is a concise way to define multiple columns or rows with the same size. This is efficient for creating uniform grid structures.
Example 5: Using minmax()
/* Defines a responsive column with a minimum and maximum size */
.grid-container {
display: grid;
/* The column will be at least 100px wide, and at most 1fr of the space */
grid-template-columns: minmax(100px, 1fr);
}
Explanation The minmax()
function defines a size range for a track. This is useful for creating responsive layouts that prevent content from becoming too compressed or too stretched.
Example 6: Using the auto keyword
/* Defines columns based on content size */
.grid-container {
display: grid;
/* The first and third columns are fixed, the middle one sizes to its content */
grid-template-columns: 100px auto 100px;
}
Explanation The auto
keyword sizes a column based on the width of its content. This ensures the column is just wide enough to hold its content without wrapping.
Example 7: Mixing Units
/* Defines a complex grid with mixed units */
.grid-container {
display: grid;
/* A combination of fixed, fractional, and content-based sizing */
grid-template-columns: 150px 1fr auto;
}
Explanation You can mix different units like pixels, fr
, and auto
to create sophisticated and responsive grid layouts that adapt to various screen sizes and content lengths.