GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR

🏁 Lesson 5: Layout with CSS Grid

⏱️ Estimated time: 35 minutes | Difficulty: Intermediate

2D Layouts

CSS Grid is the most powerful layout system available in CSS. It allows you to create complex, two-dimensional layouts with ease.

Grid = 2D Layout System

While Flexbox handles one dimension (row OR column), Grid handles both dimensions simultaneously!

.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;  /* 3 equal columns */
    grid-template-rows: auto auto;        /* 2 auto rows */
    gap: 1rem;                            /* Space between items */
}

/* Shorthand for columns */
grid-template-columns: repeat(3, 1fr);     /* 3 equal */
grid-template-columns: 200px 1fr 200px;    /* Fixed-Flex-Fixed */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Responsive! */

Placing Items

.item {
    grid-column: 1 / 3;    /* Span columns 1 to 3 */
    grid-row: 1 / 2;       /* Span row 1 */
}

/* Span shorthand */
.wide { grid-column: span 2; }  /* Span 2 columns */
.tall { grid-row: span 2; }     /* Span 2 rows */

Grid Template Areas

.layout {
    display: grid;
    grid-template-areas:
        "header  header  header"
        "sidebar content content"
        "footer  footer  footer";
    grid-template-columns: 200px 1fr 1fr;
    gap: 1rem;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer  { grid-area: footer; }

Alignment

/* Align all items */
justify-items: center;  /* Horizontal */
align-items: center;    /* Vertical */
place-items: center;    /* Both! */

/* Align individual item */
.item { justify-self: end; align-self: start; }

✅ Quick Quiz

❓ What does repeat(3, 1fr) create?

❓ Grid vs Flexbox?

❓ What does grid-template-areas do?

← Previous Next: Positioning →