Grid in CSS

Grid in CSS

Grid in CSS

Grid in CSS is a powerful layout system that allows you to create grid-based layouts with columns and rows. It allows you to define a grid container element with display: grid property and then specify its columns and rows using the grid-template-columns and grid-template-rows properties.

To create a grid, you need to define a container element with display: grid, and then define its grid template using the grid-template-columns and grid-template-rows properties. You can also use other properties such as grid-template-areas, grid-auto-rows, and grid-auto-columns to create more complex layouts.

Here’s an example of how to use CSS Grid in CSS:

HTML:

				
					<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 class="item item4">Item 4</div>
  <div class="item item5">Item 5</div>
  <div class="item item6">Item 6</div>
</div>

				
			

CSS:

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

.item {
  background-color: #ccc;
  padding: 20px;
  text-align: center;
}

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

.item2 {
  grid-row: 1 / 2;
  grid-column: 2 / 4;
}

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

.item4 {
  grid-row: 2 / 4;
  grid-column: 3 / 4;
}
.item5 {
  grid-row: 3 / 4;
  grid-column: 1 / 3;
}

.item6 {
  grid-row: 4 / 5;
  grid-column: 1 / 4;
}

				
			

In this example, we have a container element with display: grid, which makes it a grid container. We set the grid-template-columns property to repeat(3, 1fr), which creates three columns of equal width using the fr unit. We also set a grid-gap of 20px, which creates some spacing between the grid items.

For the .item elements, we set a background-color of #ccc and padding of 20px to create some visual separation. We then use the grid-row and grid-column properties to position each item within the grid. For example, item1 is positioned in rows 1 and 2, and column 1; item2 is positioned in row 1 and columns 2 to 4; and so on.

When you view this code in a web browser, you will see that the items are arranged in a grid layout with six items spread across three columns and four rows, each item positioned in a specific row and column.

Join To Get Our Newsletter
Spread the love