CSS: grid-template-columns

By Xah Lee. Date: . Last updated: .

Define columns layout

grid-template-columns
  • Define the width of each column.
  • Value is sequence of lengths separated by space, one for each column.
  • The total number of lengths means the total number of columns.
.x {
 display: grid;

 /* define a grid of 3 columns */
 grid-template-columns: 30px 60px 20px;
}

Common units

  • px → Fixed pixels
  • % → Percentage of container
  • fr → Fraction of available space (most useful)
  • auto → Fits content
  • minmax(min, max) → Responsive range
/* examples of different settings for grid-template-columns */

.xgrid {
 display: grid;

 /* 2 columns */
 grid-template-columns: 200px 200px;

 /* 2 columns, different widths */
 grid-template-columns: 200px 500px;

 /* 3 columns */
 grid-template-columns: 200px 400px 200px;

 /* 3 columns, widths by percentage */
 grid-template-columns: 20% 20% 60%;

 /* using auto for width. auto means fits element width. */
 grid-template-columns: 100px auto 150px;

 /* 4 columns, widths by comparative size. 1 fr is relative unit to the whole. */
 grid-template-columns: 1fr 1fr 1fr 5fr;

 /* 3 columns, equal width */
 grid-template-columns: 1fr 1fr 1fr;
}

Example. basic.

1
2
3
4
5
6

code

<div class="xgrid-basic-hgfSd">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
</div>
.xgrid-basic-hgfSd {
 display: grid;
 grid-template-columns: 30px 200px;
 > div {
  border: solid 1px grey;
 }
}

Example. 3col

1
2
3
4
5
6

code

<div class="xgrid-3col-ZdKb2">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
</div>
.xgrid-3col-ZdKb2 {
 display: grid;
 grid-template-columns: 30px 90px 10px;
 > div {
  border: solid 1px grey;
 }
}

Example. 4col

1
2
3
4
5
6
7
8

code

<div class="xgrid-4col-pdNCJ">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
 <div>7</div>
 <div>8</div>
</div>
.xgrid-4col-pdNCJ {
 display: grid;
 grid-template-columns: 1fr 5fr 1fr 1fr;
 > div {
  border: solid 1px grey;
 }
}

Example. 4auto

1
2
3
4
5
6
7
8

code

<div class="xgrid-4auto-RCZdQ">
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>
 <div>6</div>
 <div>7</div>
 <div>8</div>
</div>
.xgrid-4auto-RCZdQ {
 display: grid;
 grid-template-columns: auto auto auto auto;
 > div {
  border: solid 1px grey;
 }
}

CSS grid layout