CSS grid template columns
Created By: chatGPT
The CSS Grid Layout provides a flexible way to create complex layouts using rows and columns. The
grid-template-columns
property is essential for defining the number of columns and their sizes in a grid container./* Define a grid with three columns of equal width */
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
You can also specify different column sizes. For example, you might need some columns to be wider than others. Here’s how you can do that:
/* First column: 150px, second column: 1fr, third column: 2fr */
.container {
display: grid;
grid-template-columns: 150px 1fr 2fr;
}
To create columns with fixed widths and flexible sizes, you can mix units. For example, the following code creates two columns where the first column has a fixed width, and the second takes all available space:
/* First column: 100px, second column: flexible */
.container {
display: grid;
grid-template-columns: 100px auto;
}
You can also use percentages for responsiveness. Here's an example that adjusts the columns to take up 50% of the available space each, making them responsive:
/* Two equal-width columns, each taking up 50% of the container */
.container {
display: grid;
grid-template-columns: 50% 50%;
}
Combining different units and the repeat function can yield sophisticated layouts. Here’s a versatile setup with four columns where the first column is a fixed size and the rest are flexible:
/* First column: 100px, other three: flexible */
.container {
display: grid;
grid-template-columns: 100px repeat(3, 1fr);
}
To create complex layouts, you can define various column sizes according to your needs. This can include both fixed and flexible dimensions, which allows for a more dynamic interface design.
/* Three different column sizes in a grid layout */
.container {
display: grid;
grid-template-columns: 150px 200px 1fr;
}