CSS Grid
CSS Grid is a powerful layout system in CSS that allows you to create two-dimensional grid-based layouts for organizing and aligning content in a web page. With CSS Grid, you can create complex and responsive layouts easily, making it a preferred choice for building modern web designs.
Key Concepts of CSS Grid:
- Grid Container: The parent element that holds all the grid items. You define the grid container by setting its display property to
grid
. - Grid Items: The child elements of the grid container that are laid out within the grid. Grid items can be any HTML elements, and they are placed in the grid using grid lines or grid areas.
- Grid Lines: Horizontal and vertical lines that define the rows and columns of the grid. They help position the grid items within the grid container.
- Grid Tracks: The space between two adjacent grid lines, defining the rows and columns in the grid layout.
- Grid Area: A rectangular area of the grid made up of multiple grid cells. It can contain one or more grid items.
To create a CSS Grid layout, you define the grid structure on the grid container and specify how grid items are placed using various properties. Here’s a simple example:
HTML:
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
CSS:
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}
.grid-item {
background-color: #007bff;
color: white;
padding: 20px;
}
In this example, we create a 3-column grid with grid-template-columns: repeat(3, 1fr)
, which means the grid container has three columns, each with equal width (1fr
). We also add a gap between grid items with grid-gap: 10px
for spacing.
With CSS Grid, you can create advanced layouts, like nested grids, flexible and fixed-size columns, and overlapping items. It is well-supported in modern browsers and provides an efficient and flexible way to design complex and responsive web layouts.