Grid
A web page is much like a large canvas.
Just as you decide where and how to color and place elements when drawing, you must also decide where and what elements to place on a webpage.
CSS Grid emerged to address the complex layout positioning issues that arose as web services advanced.
Basic Structure and Features of Grid
CSS Grid organizes the layout in a Grid
similar to a chessboard.
A chessboard contains multiple squares, with each square available for placing chess pieces.
CSS Grid works similarly. It divides a webpage into several areas, allowing placement of desired elements freely within each area.
Basic Grid Structure
Grid consists of a Grid Container
that holds grid elements and Grid Items
that are the grid elements.
-
Grid Container: Refers to the entire grid board you create.
-
Grid Item: Each individual item placed within the grid board.
Creating a Simple Grid Structure
.container {
display: grid; /* Grid container */
}
.item {
/* Grid item */
gap: 10px; /* Space between items */
grid-column: 1 / 3; /* Spanning columns 1 to 3 */
grid-row: 1 / 2; /* Spanning rows 1 to 2 */
}
In the code above, the element with the .container
class becomes a Grid Container, and the elements inside become Grid Items.
Key Grid Properties
When configuring a layout with Grid, the following properties are used.
grid-template-columns, grid-template-rows
The grid-template-direction
property specifies how many columns and rows the container is divided into.
.container {
display: grid; /* Grid container */
grid-template-columns: 100px 200px 100px; /* Three columns, widths of 100px, 200px, and 100px respectively */
grid-template-rows: 50px 50px; /* Two rows, each 50px high */
}
The code above creates a grid board divided into three columns and two rows.
grid-column, grid-row
The grid-direction
property specifies the position of the item in terms of columns or rows. You can specify both start and end points.
.item {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
The code above specifies that the grid item spans columns from 1 to 3 and rows from 1 to 2.
Follow the highlighted sections of the code to input them yourself.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.