Junior
What is CSS Grid?
sobes.tech AI
Answer from AI
CSS Grid Layout (or simply CSS Grid) is a two-dimensional layout system in CSS. It allows managing the placement of elements both in rows (horizontally) and columns (vertically), creating complex grid structures for interface design.
The main concepts of CSS Grid include:
- Grid Container: An element to which the
display: gridordisplay: inline-gridproperty is applied. Descendants of this element become Grid Items. - Grid Items: Direct children of the Grid Container.
- Grid Lines: Dividing lines that form the grid. They can be named or have a numerical index.
- Grid Tracks: The space between two grid lines — either a column or a row.
- Grid Cells: The smallest unit of the grid, formed by the intersection of a row and a column.
- Grid Areas: A rectangular area of the grid occupying one or more cells.
Key properties for working with CSS Grid include:
For the container:
display: grid | inline-grid;grid-template-columns: Defines the columns of the grid.grid-template-rows: Defines the rows of the grid.grid-template-areas: Defines named grid areas.gap | row-gap | column-gap: Sets the gaps between cells.justify-items | align-items | place-items: Aligns content inside cells along the main and cross axes.justify-content | align-content | place-content: Aligns grid tracks within the container.
For the elements (Grid Items):
grid-column-start | grid-column-end | grid-column: Determines which column lines the element occupies.grid-row-start | grid-row-end | grid-row: Determines which row lines the element occupies.grid-area: Assigns the element to a named grid area or defines its position using lines.justify-self | align-self | place-self: Aligns the element itself within its cell.
CSS Grid provides powerful tools for creating responsive and complex layouts, significantly simplifying tasks that previously required float, inline-block, or absolute positioning.
.container {
display: grid; /* Make the element a Grid container */
grid-template-columns: 1fr 1fr 1fr; /* Create 3 columns of equal width */
grid-template-rows: auto auto; /* Create 2 rows with automatic height */
gap: 10px; /* Add gaps between cells */
}
.item {
/* Elements inside the container automatically become Grid Items */
background-color: lightblue;
padding: 20px;
text-align: center;
}
.item:nth-child(1) {
grid-column: 1 / 3; /* The first element spans columns 1 to 3 */
}