Grid
The two most important elements in a CSS raster layout are wrapper (parent) and items (children). Wrapper is really the grid, and items are the elements inside the grid.
Take the following code for example:
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>Copy the code
To make the div tag a grid, we simply set its display property to grid:
.wrapper {
display: grid;
}Copy the code
It looks something like this before we do anything else:
Columns and rows
We need to define rows and columns for the container. To split the container into two rows and three columns, use grid-template-row and grid-template-column attributes:
.wrapper {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;
}Copy the code
When we define grid-template-columns this way, we get three columns, the column length being the size we set, and grid-template-rows as well.
So we get the following result:
To see the relationship, let’s modify the code and see the result:
.wrapper {
display: grid;
grid-template-columns: 200px 50px 100px;
grid-template-rows: 100px 30px;
}Copy the code
You get the following styles:
Items
The next thing you need to know is how elements are placed in the grid system.
We create a 3 by 3 grid, and the HTML remains the same:
.wrapper {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px;
}Copy the code
There will be:
You’ll notice that our result shows a 3 by 2 grid, whereas we defined a 3 by 3 grid in our CSS code because we only have six elements in our container. If we defined nine elements in OUR HTML, the result would be a 3 by 3 grid
To reposition and resize these elements, use grid-column and grid-row attributes for the element
.item1 {
grid-column-start: 1;
grid-column-end: 4;
}Copy the code
The intent of the above code is that we want item1 to start in column 1 and end in column 4, that is, we want it to monopolize a row. Here is the result:
Grid-column-end: 4; It can be confusing, since we only have three columns in the actual result, but look at the image below to make it clear:
When the first element fills the first row, the other elements continue downward.
There’s an even simpler way to write the above code:
.item1 {
grid-column: 1 / 4;
}Copy the code
Now let’s do something a little more complicated:
.item1 {
grid-column-start: 1;
grid-column-end: 3;
}
.item3 {
grid-row-start: 2;
grid-row-end: 4;
}
.item4 {
grid-column-start: 2;
grid-column-end: 4;
}Copy the code
Here is the result of the above code. Why is the layout the way it is
That ‘s it!