grid-template-columns Property in CSS Grid Layouts
grid-template-columns specify the number and widths of columns browsers should display in the selected grid container.
Example 1: How to Create a Two-Column Grid Container
- CSS
- HTML
section {
display: grid;
grid-template-columns: 95px 1fr;
background-color: orange;
margin: 10px;
padding: 7px;
}
div {
background-color: purple;
color: white;
margin: 5px;
padding: 10px;
border-radius: 5px;
}
<section>
<div>1</div>
<div>2</div>
<div>3</div>
</section>
The snippet above used the grid-template-columns
property to display two columns of different widths in the selected <section>
grid container.
We used the fr
(fraction) unit to scale the second column relative to the fraction of available space in the grid container.
Example 2: How to Create a Three-Column Grid Container
- CSS
- HTML
section {
display: grid;
grid-template-columns: 15% 60% 25%;
background-color: orange;
margin: 10px;
padding: 7px;
}
div {
background-color: purple;
color: white;
margin: 5px;
padding: 10px;
border-radius: 5px;
}
<section>
<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>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
</section>
The snippet above used the grid-template-columns
property to display three columns of different widths in the selected <section>
grid container.
You can use the grid-auto-columns
property to specify default column widths for all the grid container's columns. For instance, grid-auto-columns: 150px
will set default widths of 150px
for all columns. But a grid-template-columns
declaration will override it.
- Use the CSS
repeat()
function to specifygrid-template-columns
values with repeated patterns. - Use the CSS
column-gap
property to create gaps between grid columns.
Overview
This article discussed what a CSS grid-template-columns
property is. We also used examples to see how it works.