0
0
CssHow-ToBeginner · 3 min read

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.

  • 1fr means one fraction of the available space.
  • You can specify fixed widths like 200px or flexible widths like auto.
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

PropertyDescriptionExample Value
displayDefines the container as a gridgrid
grid-template-columnsSets the number and size of columns1fr 1fr
gapSets space between grid items1rem
grid-template-rowsSets rows size (optional)auto
justify-itemsAligns items horizontally inside cellscenter

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.