CSS - Grid

-

Introduction to CSS Grid

CSS Grid is a powerful 2-dimensional layout system in CSS that lets web developers create complex layouts with rows and columns. It gives more control and flexibility compared to traditional layout methods like floats and positioning.

With CSS Grid, you can define a grid container and divide it into a grid of rows and columns. You can then place grid items into the cells of the grid, specifying their size, position, and alignment. This makes it easier to create responsive layouts that adapt to different screen sizes and devices.

Example: HTML Code for a Grid Container

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

One of the main advantages of CSS Grid is its ability to handle both rows and columns simultaneously. Unlike flexbox, which primarily focuses on one-dimensional layouts, CSS Grid enables you to create multi-dimensional layouts with ease. You can define the size and placement of grid items along both the horizontal and vertical axes.

CSS Grid also introduces new concepts and terminology, such as grid lines, tracks, and areas. Grid lines are the dividing lines that define the grid's rows and columns, while tracks are the spaces between two adjacent grid lines. Grid areas allow you to define named regions within the grid, making it simpler to place and align items.

Example: CSS Code to Define a Grid Layout

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}

Overall, CSS Grid is a powerful tool that simplifies the process of creating complex and responsive layouts. It offers a more intuitive and efficient way to structure web pages compared to traditional layout techniques.

Grid Container and Grid Items

In CSS Grid, there are two main concepts: the grid container and grid items.

Grid Container

The grid container is the element that holds the grid items. It is the parent element that defines the grid layout. To create a grid container, you apply the display: grid or display: inline-grid property to an element.

Example: Creating a Grid Container

.container {
  display: grid;
}

When you set display: grid, the element becomes a block-level grid container. On the other hand, using display: inline-grid creates an inline-level grid container.

The grid container establishes a new grid formatting context for its contents. It defines the grid's rows and columns and controls how the grid items are placed and sized within the grid.

Grid Items

Grid items are the direct children of the grid container. They are the elements that are placed into the grid cells defined by the container.

By default, grid items are automatically placed into the grid cells in the order they appear in the source code. Each item occupies one cell in the grid, but you can control their placement and spanning using CSS Grid properties.

Example: HTML Code for Grid Items

<div class="container">
  <div class="item item1">Item 1</div>
  <div class="item item2">Item 2</div>
  <div class="item item3">Item 3</div>
</div>

Grid items can be styled individually using CSS properties like grid-row-start, grid-row-end, grid-column-start, grid-column-end, or the shorthand properties grid-row and grid-column. These properties allow you to specify the grid lines where an item should start and end, determining its position and size within the grid.

Grid items can also be assigned to named grid areas using the grid-area property, which provides a more semantic way of positioning items within the grid.

It's important to note that only the direct children of the grid container are considered grid items. Nested elements within grid items are not part of the grid layout and do not participate in the grid's sizing and positioning.

Creating a Grid

To create a grid using CSS Grid, you need to define the rows and columns of the grid and specify the spacing between grid items.

Defining Rows and Columns

To define the rows and columns of a grid, you use the grid-template-rows and grid-template-columns properties on the grid container. These properties let you specify the size of each row and column using values like pixels, percentages, or the fr unit.

The fr unit represents a fraction of the available space in the grid container. It lets you divide the space proportionally among rows or columns.

Example: Defining Rows and Columns

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

In the example above, the grid container has two rows with heights of 100 pixels and 200 pixels, respectively. It also has three columns, where the first and third columns each take up one fraction of the available space, and the second column takes up two fractions.

You can also use the repeat() function to create a repeating pattern of rows or columns with a specified size.

Example: Using repeat() function

.container {
  display: grid;
  grid-template-rows: repeat(3, 150px);
  grid-template-columns: repeat(2, 1fr);
}

In this example, the grid container has three rows, each with a height of 150 pixels, and two columns that each take up an equal fraction of the available space.

Gap Between Grid Items

To control the spacing between grid items, you can use the grid-gap property on the grid container. It is a shorthand property for grid-row-gap and grid-column-gap, which specify the gap between rows and columns, respectively.

Example: Using grid-gap property

.container {
  display: grid;
  grid-template-rows: repeat(3, 150px);
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
}

In the example above, the grid-gap property sets a gap of 20 pixels between both rows and columns. You can also use different values for grid-row-gap and grid-column-gap to set different spacing for rows and columns.

Example: Different values for grid-row-gap and grid-column-gap

.container {
  display: grid;
  grid-template-rows: repeat(3, 150px);
  grid-template-columns: repeat(2, 1fr);
  grid-row-gap: 10px;
  grid-column-gap: 20px;
}

In this example, the grid-row-gap property sets a gap of 10 pixels between rows, while the grid-column-gap property sets a gap of 20 pixels between columns.

By defining rows, columns, and gaps, you can create a grid structure that suits your layout requirements. CSS Grid provides a flexible and powerful way to control the arrangement of elements within a grid container.

Placing Grid Items

In CSS Grid, you can place grid items into specific cells within the grid using grid lines and tracks. Grid lines are the dividing lines that define the grid's rows and columns, while grid tracks are the spaces between two adjacent grid lines.

Grid Lines and Tracks

Grid lines are numbered starting from 1, and they represent the lines that form the grid. The line numbers increase from left to right for columns and from top to bottom for rows. Grid tracks are the spaces between two adjacent grid lines. They represent the rows and columns of the grid.

Example: HTML Layout for Grid Container

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

Example: CSS for Grid Layout

.grid-container {
  display: grid;
  grid-template-rows: repeat(2, 1fr);
  grid-template-columns: repeat(2, 1fr);
}

The grid has two rows and two columns, creating four grid tracks. The grid lines are numbered from 1 to 3 for both rows and columns.

Positioning Items Using Grid Lines

To position grid items using grid lines, you can use the grid-row-start, grid-row-end, grid-column-start, and grid-column-end properties on the grid items. These properties let you specify the grid lines where an item should start and end.

Example: CSS for Positioning Grid Items

.grid-item:nth-child(1) {
  grid-row-start: 1;
  grid-row-end: 3;
  grid-column-start: 1;
  grid-column-end: 2;
}

The first grid item is positioned to start at row line 1 and end at row line 3, spanning two rows. It starts at column line 1 and ends at column line 2, occupying one column.

You can also use the shorthand properties grid-row and grid-column to specify the start and end lines in a more concise way.

Example: CSS Shorthand for Positioning Grid Items

.grid-item:nth-child(2) {
  grid-row: 1 / 2;
  grid-column: 2 / 3;
}

The second grid item starts at row line 1 and ends at row line 2, occupying one row. It starts at column line 2 and ends at column line 3, occupying one column.

Spanning Items Across Multiple Cells

To make a grid item span across multiple cells, you can use the grid-row and grid-column shorthand properties and specify the start and end lines separated by a slash (/).

Example: CSS for Spanning Grid Items

.grid-item:nth-child(3) {
  grid-row: 2 / 3;
  grid-column: 1 / 3;
}

The third grid item starts at row line 2 and ends at row line 3, occupying one row. It starts at column line 1 and ends at column line 3, spanning across two columns.

By using grid lines and tracks, you can control the placement and spanning of grid items within the grid container. This gives you flexibility in creating layouts and positioning elements where you want them.

Grid Areas and Templates

CSS Grid lets you define grid areas and assign grid items to those areas using grid templates. This allows you to create semantic and readable grid layouts.

Defining Grid Areas

To define grid areas, you use the grid-template-areas property on the grid container. This property lets you create a visual representation of the grid layout using strings.

Each string represents a row in the grid, and each value within the string represents a cell in that row. You can use any name you want for the grid areas, or you can use a dot (.) to represent an empty cell.

Example: Defining Grid Areas

.grid-container {
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  grid-template-columns: repeat(3, 1fr);
  grid-template-areas:
    "header header header"
    "sidebar content content"
    "footer footer footer";
}

We define a grid with three rows and three columns using the grid-template-rows and grid-template-columns properties. Then, we use the grid-template-areas property to define grid areas.

The grid areas are defined as follows:

Area Description
header The first row, spans across all three columns
sidebar The second row, occupies the first column
content The second row, occupies the remaining two columns
footer The third row, spans across all three columns

By using grid areas, you can create an intuitive and readable structure for your grid layout.

Assigning Items to Grid Areas

Once you have defined the grid areas using grid-template-areas, you can assign grid items to those areas using the grid-area property on the grid items.

Example: Assigning Items to Grid Areas

.header {
  grid-area: header;
}

.sidebar {
  grid-area: sidebar;
}

.content {
  grid-area: content;
}

.footer {
  grid-area: footer;
}

We assign each grid item to its corresponding grid area using the grid-area property. The value of grid-area should match the name of the grid area defined in the grid-template-areas property.

By assigning items to grid areas, you can easily control their placement within the grid without having to specify exact grid lines or tracks.

Grid areas and templates provide a way to create semantic and flexible grid layouts. They allow you to define the structure of your grid using areas and then assign items to those areas using a simple and readable syntax.

Aligning and Justifying Items

CSS Grid provides properties to control the alignment and justification of grid items within their cells and the grid container itself. These properties give you control over the horizontal and vertical positioning of items.

Aligning Items Within Grid Cells

To align items within their grid cells, you can use the justify-items and align-items properties on the grid container.

The justify-items property controls the horizontal alignment of grid items within their cells. It can take these values:

Value Description
start Aligns items to the left side of their cells.
end Aligns items to the right side of their cells.
center Centers items horizontally within their cells.
stretch (default) Items fill the entire width of their cells.

justify-items Example

.grid-container {
  display: grid;
  justify-items: center;
}

The align-items property controls the vertical alignment of grid items within their cells. It can take these values:

Value Description
start Aligns items to the top of their cells.
end Aligns items to the bottom of their cells.
center Centers items vertically within their cells.
stretch (default) Items fill the entire height of their cells.

align-items Example

.grid-container {
  display: grid;
  align-items: end;
}

Aligning the Grid Within Its Container

In addition to aligning items within grid cells, you can also align the entire grid within its container using the justify-content and align-content properties on the grid container.

The justify-content property controls the horizontal alignment of the grid within its container. It can take these values:

Value Description
start Aligns the grid to the left side of the container.
end Aligns the grid to the right side of the container.
center Centers the grid horizontally within the container.
stretch (default) The grid fills the entire width of the container.
space-between Distributes the grid tracks evenly with equal space between them.
space-around Distributes the grid tracks evenly with equal space around them.
space-evenly Distributes the grid tracks evenly with equal space between and around them.

justify-content Example

.grid-container {
  display: grid;
  justify-content: space-between;
}

The align-content property controls the vertical alignment of the grid within its container. It can take the same values as justify-content:

align-content Example

.grid-container {
  display: grid;
  align-content: center;
}

By using these alignment and justification properties, you can adjust the positioning of grid items within their cells and the grid within its container. This allows you to create visually appealing and well-aligned grid layouts.

Responsive Grid Layouts

CSS Grid gives you tools for making responsive layouts that adapt to different screen sizes and devices. By combining grid properties with media queries and automatic sizing, you can make flexible and dynamic grid layouts.

Using Media Queries

Media queries let you apply different styles based on the device or viewport. When making responsive grid layouts, you can use media queries to change the grid template, item placement, and alignment based on different screen sizes.

Example: CSS Grid with Media Queries

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}

@media screen and (max-width: 768px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 480px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
}

In the example above, we define a grid container with three equal-width columns using the grid-template-columns property and repeat() function. We also add a gap of 20 pixels between grid items using grid-gap.

Then, we use media queries to change the grid template based on different screen sizes. For screens with a maximum width of 768 pixels, we change the grid to have two equal-width columns. For screens with a maximum width of 480 pixels, we change the grid to have a single column.

By changing the grid template using media queries, you can make a responsive layout that adapts to different screen sizes. You can also change other grid properties, such as item placement and alignment, within the media queries to further customize the layout for different devices.

Automatic Grid Columns and Rows

CSS Grid provides the auto-fit and auto-fill keywords that can be used with the repeat() function to make automatic grid columns and rows. These keywords allow the grid to adapt its layout based on the available space and the size of grid items.

The auto-fit keyword makes as many tracks as needed to fit the grid items within the container, collapsing any empty tracks. This is useful when you want the grid items to expand and fill the available space.

Example: CSS Grid with auto-fit

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

In this example, we use repeat(auto-fit, minmax(200px, 1fr)) to make grid columns. The minmax() function specifies a minimum width of 200 pixels and a maximum width of 1 fraction unit (1fr). The auto-fit keyword makes sure that the grid items are placed in the available space, making as many columns as needed.

The auto-fill keyword, on the other hand, makes as many tracks as possible without collapsing empty tracks. This is useful when you want to keep a consistent grid structure even if there are fewer grid items than available tracks.

Example: CSS Grid with auto-fill

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

In this example, repeat(auto-fill, minmax(200px, 1fr)) is used to make grid columns. The auto-fill keyword makes as many columns as possible based on the minimum width of 200 pixels and the maximum width of 1fr. If there are fewer grid items than available tracks, the empty tracks will be kept.

By using auto-fit and auto-fill with the repeat() function, you can make responsive grid layouts that automatically change the number and size of columns and rows based on the available space and the content of the grid items.

Combining media queries and automatic sizing techniques allows you to make very flexible and responsive grid layouts that adapt to different screen sizes and content needs. This makes CSS Grid a powerful tool for building responsive web designs.