CSS Grid

Photo by Erol Ahmed on Unsplash

CSS Grid

·

2 min read

Table of contents

CSS Grid is a powerful layout system that uses a two-dimensional grid to arrange website elements. It defines rows and columns, allowing you to position elements exactly where you want them, span them across multiple squares, and even overlap them for creative effects.

Layman Perspective

Think of grid as chef's pantry with shelves and compartments. Each shelf in a row, each compartment a column. Instead of storing ingredients, we are placing website elements within these spaces, organizing them neatly and visually appealing way.

Now lets discuss different properties of the grid

  • display: grid ---> Enables grid behavior of the element.

  • grid-template-columns ---> Defines column structure.

  • grid-template-rows ---> Defines the row structure.

  • grid-column ---> positions items within grid columns.

  • grid-rows ---> positions items within grid rows.

Example:

<!DOCTYPE html>
<html>
<head>
<title>CSS Grid Example</title>
<link rel="stylesheet" href="../CSS/grid.css">
</head>
<body>

<div class="grid-container">
  <div class="item item-1">Item 1</div>
  <div class="item item-2">Item 2</div>
  <div class="item item-3">Item 3</div>
  <div class="item item-4">Item 4</div>
</div>

</body>
</html>
.grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr; 
    grid-template-rows: repeat(3, 100px); 
    grid-gap: 10px; 
  }

  .item {
    background-color: lightseagreen;
    padding: 20px;
    text-align: center;
  }


  .item-1 {
    grid-column: 1;
    grid-row: 1 / 3; 
  }

  .item-2 {
    grid-column: 2;
    grid-row: 1 / 2; 
  }

  .item-3 {
    grid-column: 2;
    grid-row: 3;
  }

  .item-4 {
    grid-column: 1;
    grid-row: 3;
  }

Output: