CSS for Web Development

0% completed

Previous
Next
Defining columns and rows

CSS Grid lets you split a container into columns and rows. This helps you design layouts with specific areas for content. You can use grid properties to create a fixed number of columns and rows with the sizes you choose.

You use properties like grid-template-columns and grid-template-rows to set up your grid layout. These properties let you control the size and number of columns and rows. You can use fixed sizes (like pixels), flexible sizes (using fractions), or other units.

Syntax

Follow the code block below to define columns and rows in a grid container:

.grid-container { display: grid; /* Establishes the element as a grid container */ /* Define columns - sizes can be in pixels, fractions (fr), percentages, etc. */ grid-template-columns: 100px 200px; /* Two columns: first is 100px, second is 200px */ /* Define rows - sizes can be fixed or dynamic */ grid-template-rows: 50px auto; /* Two rows: first is 50px, second takes up remaining space */ }

Explanation:

  • grid-template-columns:
    • Defines the widths of each column.
    • In the example, there are two columns: the first is 100px wide, and the second is 200px wide.
  • grid-template-rows:
    • Defines the heights of each row.
    • In the example, the first row is 50px high. The second row uses auto to fill remaining space based on content or container size.

Example 1: Fixed Size Columns and Rows

In this example, we create a grid with two fixed columns and two fixed rows. This lets you see how the grid divides the space into defined blocks.

HTML

. . . .

Explanation:

  • Grid Container:
    • The container creates a grid with two columns and two rows.
  • Fixed Sizes:
    • The columns are 100px and 200px wide.
    • The rows are 50px and 100px tall.
  • Grid Gap:
    • A 10px gap is placed between the items.
  • Outcome:
    • Four grid items are placed in the grid, each occupying its own cell.

Example 2: Using Flexible Sizes with Fraction Units

In this example, we use fraction units (fr) to create flexible columns and rows. Fraction units allow columns and rows to share space proportionally.

HTML

. . . .

Explanation:

  • Flexible Columns:
    • Using 1fr 2fr makes the second column twice as wide as the first.
  • Flexible Rows:
    • The first row has a fixed height of 100px.
    • The second row uses auto, which means its height will depend on its content.
  • Outcome:
    • The grid adjusts itself based on the available space, and items scale proportionally.

This lesson demonstrates how to define columns and rows in a CSS Grid. By using fixed values, fraction units, and auto-sizing, you can precisely control the layout of your grid container and design flexible, dynamic layouts.

.....

.....

.....

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