How to Create Two Column Layout with Grid in CSS
Use
display: grid; on a container and set grid-template-columns to define two columns, for example grid-template-columns: 1fr 1fr; creates two equal columns. Place your content inside this container to see the two column layout.Syntax
To create a two column layout with CSS Grid, you use the display: grid; property on a container. Then, define the columns using grid-template-columns. Each value represents a column size.
1frmeans one fraction of the available space.- You can specify fixed widths like
200pxor flexible widths likeauto.
css
.container {
display: grid;
grid-template-columns: 1fr 1fr;
}Example
This example shows a container with two equal columns. Each column holds some text. The grid divides the container horizontally into two equal parts.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Two Column Grid Layout</title> <style> .container { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; padding: 1rem; border: 2px solid #333; } .box { background-color: #cce5ff; padding: 1rem; border-radius: 4px; text-align: center; font-family: Arial, sans-serif; } </style> </head> <body> <div class="container"> <div class="box">Column 1 content</div> <div class="box">Column 2 content</div> </div> </body> </html>
Output
A webpage showing a bordered container with two side-by-side blue boxes labeled 'Column 1 content' and 'Column 2 content', each taking half the container width with spacing between them.
Common Pitfalls
Common mistakes when creating two column layouts with grid include:
- Not setting
display: grid;on the container, so grid properties won't work. - Forgetting to define
grid-template-columns, which means no columns are created. - Using fixed widths without considering responsiveness, which can break layout on small screens.
- Not adding gap or spacing, making columns stick together visually.
css
/* Wrong: Missing display grid */ .container { grid-template-columns: 1fr 1fr; } /* Right: Include display grid */ .container { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
Quick Reference
| Property | Description | Example Value |
|---|---|---|
| display | Defines the container as a grid | grid |
| grid-template-columns | Sets the number and size of columns | 1fr 1fr |
| gap | Sets space between grid items | 1rem |
| grid-template-rows | Sets rows size (optional) | auto |
| justify-items | Aligns items horizontally inside cells | center |
Key Takeaways
Use display: grid and grid-template-columns to create columns.
1fr divides space equally between columns.
Add gap for spacing between columns.
Always set display: grid on the container.
Test layout on different screen sizes for responsiveness.