CSS Grid


🔹 What is CSS Grid?

CSS Grid Layout is a two-dimensional layout system in CSS. Unlike Flexbox (which is one-dimensional), Grid lets you work with both rows and columns, making it perfect for building full-page layouts, dashboards, galleries, and complex web designs.

It allows developers to position elements precisely and create responsive layouts with less code.


🔸 Why Use CSS Grid?

  • Full control over rows and columns

  • Responsive design with fewer media queries

  • Gap management without margin hacks

  • Great for grid-based designs like galleries, cards, layouts, etc.


🔸 Basic Grid Syntax

HTML:
<div class="grid-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
CSS:
.grid-container {
  display: grid;
  grid-template-columns: auto auto;
  gap: 10px;
}

This creates a 2-column grid with a 10px gap.


🔸 Main Grid Properties

Property Description
display: grid Defines the container as a grid
grid-template-columns Sets number & width of columns
grid-template-rows Sets number & height of rows
gap Space between rows and columns
grid-column / grid-row Position and span for grid items
grid-area Assigns a name to a section of the grid

🔸 Example: Fixed and Flexible Grid

.grid-container {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: 100px auto;
}

🔸 Responsive Grid with repeat() and minmax()

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

This adjusts the number of columns based on available screen width.


Practice Questions

✅ Write CSS for the following:

Q1. Create a 3-column grid with equal-width columns.

Q2. Add a 20px gap between grid items.

Q3. Make a grid layout with 2 fixed columns and 1 flexible column.

Q4. Create a responsive grid using auto-fit and minmax().

Q5. Span a grid item across 2 columns.

Q6. Position one grid item in row 2, column 3.

Q7. Create a 2x2 grid layout.

Q8. Center all grid items horizontally and vertically.

Q9. Add different row heights using grid-template-rows.

Q10. Use grid-area to name and place layout sections.


Go Back Top