CSS grid-template-columns Property Tutorial

In this section, we will learn what the grid-template-columns property is and how to use it in CSS.

Click here to run the example of grid-template-columns property.

CSS grid-template-columns Property Definition and Usage

In grid system, the area between two vertical lines that move along each other is called track (AKA column).

CSS grid-template-columns

Now, when we use a grid system in our design, we need to set the number of columns for that grid as well.

This is done with the help of a CSS property called `grid-template-columns`.

Note: In grid system, there’s another property named `grid-auto-columns` that is used for creating implicit columns and if set, browsers will create a new column when it’s needed.

CSS grid-template-columns Property Syntax

grid-template-columns: first-column-width second-column-width nth-column-width;

CSS grid-template-columns Property Value

Any number we set for the value of `grid-template-columns` it represents the width of a new column.

So, for example, if we set 3 different values for this property, it means we need three columns for the target grid with the specified width for each column.

For example:

grid-template-columns: 10vw 200px 15em;

In the example above, first of all, the order is to create 3 columns because we used 3 values for this property.

Secondly, it means:

  • The first column should have the width of 10vw (10 percent of the viewport width).
  • The second column should have the width of 200px.
  • The third column should have the width of 15em.

Note: By default, a grid system has one column and one row and if we want to increase the number of rows we can use the CSS property ‘grid-template-rows` which you can read about it in its section.

We can also set name for one or multiple lines between each column.

Here’s the syntax:

grid-template-columns: [line-one-name line-one-another-name] 100px [line-two-name] 200px [line-x-name]

As you can see, in order to set a name for each line, we should use open and close brackets and within these brackets we can set one or multiple names for one line. Each name is separated using a white space.

We can use these names just like numbers when we want to position a grid-item in a specific place on the grid.

The advantage of using names over numbers is the fact that names can help developers recognize what line belongs to what area of that grid.

Example: grid-template-columns property in CSS

See the Pen grid-template-columns property in CSS by Omid Dehghan (@enjoytutorials1) on CodePen.

Example: creating columns with names using CSS grid-template-columns property

See the Pen creating columns with names using CSS grid-template-columns property by Omid Dehghan (@enjoytutorials1) on CodePen.

Note: the `fr unit`, `minmax()` and `repeat( )` functions are also related to `grid-template-columns` so make sure you read those sections as well.


Top Technologies