CSS for Web Development

0% completed

Previous
Next
Grid container and grid items

CSS Grid is a powerful tool for building layouts that are not only flexible but also uniquely structured. In a grid layout, one element becomes the grid container, and all of its direct children automatically turn into grid items. This separation allows you to control the overall grid structure while also styling individual items in ways that are not as easily achievable with other layout methods.

When you declare a container as a grid, you can define rows, columns, and gaps between the items, and even have items span multiple rows or columns. This lesson provides unique examples that show how CSS Grid can be used to build distinct layouts.

Syntax

Follow the code block below to create a grid container and work with grid items:

/* Create a grid container */ .grid-container { display: grid; /* Establishes a grid layout */ } /* Style grid items (all direct children become grid items) */ .grid-item { /* You can add individual styles to grid items here */ }

Explanation:

  • display: grid;
    • Turns an element into a grid container, enabling grid layout features.
  • Grid Items:
    • Every direct child of the grid container automatically becomes a grid item, which you can then style and position.

Example 1: Image Gallery Layout

In this example, we create an image gallery with a grid that displays items in three equal columns. This layout automatically places items into the grid without needing to specify positions manually.

HTML

. . . .

Explanation:

  • Grid Setup:
    • grid-template-columns: repeat(3, 1fr); creates three equal-width columns.
    • The gap property adds 15px spacing between all grid items.
  • Outcome:
    • The images (or placeholders in this case) are neatly arranged in a three-column layout, automatically filling rows as needed.

These unique examples demonstrate how CSS Grid works beyond typical flexbox implementations. They highlight powerful grid features like auto-placement, explicit grid definitions, and spanning, which enable you to create versatile and intricate web layouts easily.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next