0
0
CssConceptBeginner · 3 min read

What is display grid in CSS: Simple Explanation and Examples

display: grid in CSS is a layout system that lets you arrange elements in rows and columns, like a table but more flexible. It helps create complex, responsive designs by defining grid areas and placing items precisely.
⚙️

How It Works

Imagine you have a blank sheet divided into squares, like a chessboard. display: grid turns a container into that sheet, where you can place items into specific squares or groups of squares. You decide how many rows and columns the grid has and how big each cell should be.

Unlike older layout methods, grid lets you control both rows and columns at the same time, making it easier to build neat, organized designs. You can think of it like arranging furniture in a room by placing each piece exactly where you want it on a floor plan.

💻

Example

This example creates a simple 2-column grid with 4 items placed in order.

html
html {
  font-family: Arial, sans-serif;
}
.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  max-width: 400px;
  margin: 20px auto;
  padding: 10px;
  background-color: #f0f0f0;
}
.item {
  background-color: #4CAF50;
  color: white;
  padding: 20px;
  text-align: center;
  border-radius: 5px;
  font-weight: bold;
}

<body>
  <div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
  </div>
</body>
Output
A centered box with a light gray background containing four green boxes labeled 1, 2, 3, and 4 arranged in two columns and two rows with space between them.
🎯

When to Use

Use display: grid when you want to create layouts that need precise control over rows and columns. It is perfect for building photo galleries, dashboards, forms, and any design where items should line up neatly in both directions.

Grid is especially helpful for responsive design because you can easily change the number of columns or rows based on screen size, making your site look good on phones, tablets, and desktops.

Key Points

  • display: grid creates a grid container for layout.
  • You define rows and columns with grid-template-columns and grid-template-rows.
  • Grid items can span multiple rows or columns.
  • It simplifies complex layouts compared to older methods like floats or flexbox.
  • Supports responsive design by adjusting grid structure on different screens.

Key Takeaways

display: grid lets you arrange elements in rows and columns easily.
You can control the size and position of grid cells for precise layouts.
Grid is great for complex and responsive designs.
It works like a flexible chessboard for placing content.
Use grid to replace older, harder layout methods for cleaner code.