How to Use grid-column-start and grid-column-end in CSS
Use
grid-column-start and grid-column-end to specify where a grid item begins and ends horizontally in a CSS grid layout. These properties accept line numbers, names, or span values to control the item's column position and size.Syntax
grid-column-start sets the starting vertical grid line for an item, and grid-column-end sets the ending vertical grid line. You can use numbers (grid lines), named lines, or the span keyword to cover multiple columns.
- Number: The line number to start or end at.
- Named line: A custom name defined in the grid template.
- Span: How many columns the item should span.
css
grid-column-start: <start-line>; grid-column-end: <end-line>;
Example
This example shows a grid container with 4 columns. The blue box starts at column line 2 and ends at column line 4, so it covers columns 2 and 3.
css
html, body {
height: 100%;
margin: 0;
font-family: Arial, sans-serif;
}
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
padding: 20px;
background: #f0f0f0;
height: 100vh;
align-items: center;
justify-items: center;
}
.box {
background-color: #4a90e2;
color: white;
padding: 20px;
font-weight: bold;
border-radius: 8px;
}
.box1 {
grid-column-start: 2;
grid-column-end: 4;
}Output
<div class="container">
<div class="box box1">Box spans columns 2 to 3</div>
</div>
Common Pitfalls
Common mistakes include:
- Using
grid-column-startandgrid-column-endvalues that are out of the grid's range, causing the item not to appear as expected. - Confusing line numbers with column numbers; lines are the grid lines between columns, so line 1 is before the first column.
- Not using
spancorrectly, which should be followed by a number to indicate how many columns to cover.
css
/* Wrong: Using column number instead of line number */ .box { grid-column-start: 1; grid-column-end: 3; /* This is correct if grid has at least 3 lines */ } /* Right: Using span keyword to cover 2 columns */ .box { grid-column-start: 2; grid-column-end: span 2; }
Quick Reference
| Property | Description | Example Values |
|---|---|---|
| grid-column-start | Sets the starting vertical grid line | 1, 2, 'line-name', span 2 |
| grid-column-end | Sets the ending vertical grid line | 3, 4, 'line-name', span 3 |
Key Takeaways
Use grid-column-start and grid-column-end to control horizontal placement of grid items by specifying grid lines or span.
Grid lines are numbered starting at 1 before the first column, not the columns themselves.
The span keyword lets you cover multiple columns easily without calculating end lines.
Ensure your line numbers or names exist in the grid template to avoid layout issues.
You can combine these properties or use the shorthand grid-column for simpler code.