Grid rows and columns help you organize content neatly on a page. They let you create layouts like a table but with more control and flexibility.
0
0
Grid rows and columns in CSS
Introduction
When you want to arrange items in neat rows and columns, like a photo gallery.
When you need a responsive layout that adjusts to different screen sizes.
When you want to align content both horizontally and vertically easily.
When you want to create complex page layouts without using floats or positioning.
When you want to control the size of rows and columns precisely.
Syntax
CSS
.container { display: grid; grid-template-columns: <track-size> <track-size> ...; grid-template-rows: <track-size> <track-size> ...; }
grid-template-columns sets the width of each column.
grid-template-rows sets the height of each row.
Examples
This creates 3 columns with widths 100px, 200px, and 100px, and 2 rows with heights 50px and 100px.
CSS
.container { display: grid; grid-template-columns: 100px 200px 100px; grid-template-rows: 50px 100px; }
This creates 3 equal columns that share available space and 2 rows each 150px tall.
CSS
.container { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: 150px 150px; }
This creates 2 columns where the second is twice as wide as the first, and rows adjust height automatically based on content.
CSS
.container { display: grid; grid-template-columns: 1fr 2fr; grid-template-rows: auto auto; }
Sample Program
This example creates a grid with 3 columns and 2 rows. The middle column is twice as wide as the others. Each grid item is centered with a background color and number.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Grid Rows and Columns Example</title> <style> .grid-container { display: grid; grid-template-columns: 1fr 2fr 1fr; grid-template-rows: 100px 150px; gap: 10px; border: 2px solid #333; padding: 10px; } .grid-item { background-color: #8ac6d1; display: flex; align-items: center; justify-content: center; font-weight: bold; color: #fff; border-radius: 5px; } </style> </head> <body> <main> <section class="grid-container" aria-label="Example grid with rows and columns"> <div class="grid-item">1</div> <div class="grid-item">2</div> <div class="grid-item">3</div> <div class="grid-item">4</div> <div class="grid-item">5</div> <div class="grid-item">6</div> </section> </main> </body> </html>
OutputSuccess
Important Notes
Use gap to add space between rows and columns easily.
Use fr units to divide space proportionally.
Rows and columns can have fixed sizes (like px), flexible sizes (like fr), or automatic sizes (auto).
Summary
Grid rows and columns define the structure of your layout.
You can mix fixed and flexible sizes for precise control.
Grid makes it easy to create neat, responsive designs.