MakeW3web

CSS Grid basics

CSS Grid is a powerful layout model in CSS that allows you to create complex, multi-dimensional layouts in a very intuitive way. It uses a grid of rows and columns to lay out elements on a web page.

Creating a CSS Grid Container

To create a CSS Grid container, you need to set the `display` property of the container to `grid`. Here's an example:

HTML:

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

CSS:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
In this example, the `.container` element is set to `display: grid`, which makes it a CSS Grid container. The `grid-template-columns` property is used to define the width of each column in the grid.

Defining Grid Rows and Columns

In a CSS Grid layout, you can define the number of rows and columns in the grid, as well as their size and position. Here are some of the most commonly used properties for defining grid rows and columns:

`grid-template-columns` and `grid-template-rows`

These properties define the number and size of the columns and rows in the grid. You can use a variety of units to define the size of each column or row, such as `px`, `fr`, `em`, and `%`.

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

In this example, the grid has three columns with widths of 1 fraction, 2 fractions, and 1 fraction respectively. It also has two rows with heights of 100 pixels and 200 pixels respectively.

`grid-column` and `grid-row`

These properties allow you to specify which column or row a grid item should span. You can use a combination of the `grid-column-start`, `grid-column-end`, `grid-row-start`, and `grid-row-end` properties to define the start and end positions of a grid item.

.item {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}

In this example, the `.item` element spans two columns (from column 1 to column 3) and one row (from row 1 to row 2).

Conclusion

CSS Grid is a powerful and flexible layout model in CSS that can make creating complex layouts much easier. By using the properties outlined above, you can create multi-dimensional layouts with minimal CSS code.

Was this page helpful?