How to Use grid-column in CSS: Simple Guide with Examples
The
grid-column property in CSS sets where a grid item starts and ends horizontally within a grid container. You can specify it using line numbers, span keywords, or named grid lines to control the item's column position and width.Syntax
The grid-column property is a shorthand for grid-column-start and grid-column-end. It defines the starting and ending grid lines for a grid item horizontally.
grid-column: <start-line> / <end-line>;- sets start and end lines by number or name.grid-column: span <number>;- makes the item span across a number of columns.grid-column: auto;- default, lets the item auto-place.
css
grid-column: <start-line> / <end-line>; grid-column: span <number>; grid-column: auto;
Example
This example shows a grid container with 4 columns. The second item uses grid-column: 2 / 4; to start at column line 2 and end before column line 4, spanning 2 columns.
html, css
html, body {
height: 100%;
margin: 0;
font-family: Arial, sans-serif;
}
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
padding: 10px;
background: #f0f0f0;
}
.item {
background: #4a90e2;
color: white;
padding: 20px;
text-align: center;
border-radius: 4px;
}
.item2 {
grid-column: 2 / 4;
}Output
A grid with 4 equal columns and 4 items. The second item is wider, spanning columns 2 and 3, visually twice as wide as others.
Common Pitfalls
Common mistakes when using grid-column include:
- Using line numbers that don't exist in the grid, causing the item to not display as expected.
- Forgetting that grid lines start at 1, not 0.
- Mixing
spanwith explicit line numbers incorrectly. - Not setting
display: grid;on the container, sogrid-columnhas no effect.
css
/* Wrong: grid-column lines out of range */ .item { grid-column: 1 / 10; /* If grid has fewer lines, this breaks layout */ } /* Correct: use valid lines or span */ .item { grid-column: 1 / 4; } /* Wrong: mixing span and line number incorrectly */ .item { grid-column: span 2 / 4; /* Invalid syntax */ } /* Correct span usage */ .item { grid-column: span 2; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| grid-column | Sets start and end column lines | grid-column: 2 / 5; |
| grid-column-start | Sets the start column line | grid-column-start: 3; |
| grid-column-end | Sets the end column line | grid-column-end: span 2; |
| span keyword | Makes item span multiple columns | grid-column: span 3; |
| auto | Default placement | grid-column: auto; |
Key Takeaways
Use
grid-column to control horizontal placement and width of grid items.Specify start and end lines by number or use
span to cover multiple columns.Grid lines start at 1, so avoid zero or out-of-range numbers.
Always set
display: grid; on the container for grid properties to work.Check your grid's column count to avoid invalid line references.