2KB Vue
CSS Grid and Flexbox
CSS Grid and Flexbox are two powerful layout systems in CSS, each designed to handle different kinds of layout needs. Here's a brief overview of each:
CSS Grid
CSS Grid is a two-dimensional layout system, meaning it can handle both rows and columns. It's ideal for more complex, grid-based layouts.
Key Features:
- Two-Dimensional Layout: CSS Grid works on both axes (horizontal and vertical), making it perfect for creating complex layouts where items are aligned in both rows and columns.
- Explicit Grid: You can define the grid structure explicitly using
grid-template-rows,grid-template-columns, andgrid-template-areas. - Placement Control: Items can be placed precisely using grid line numbers or named areas, offering fine control over where items are placed.
- Gaps: The
grid-gapproperty (orgapin newer CSS) allows for easy spacing between grid items. - Responsive Design: CSS Grid can easily adapt to responsive design, with different grid layouts for different screen sizes.
Example:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 10px;
}
.item1 {
grid-column: 1 / 3;
grid-row: 1;
}
Flexbox
Flexbox (Flexible Box Layout) is a one-dimensional layout system, perfect for layouts in a single direction (either a row or a column).
Key Features:
- One-Dimensional Layout: Flexbox is designed for laying out items in a single direction, either horizontally or vertically.
- Flex Containers and Items: A flex container's children become flex items that can be aligned, spaced, and ordered.
- Alignment and Justification: Flexbox provides powerful alignment options such as
justify-content,align-items, andalign-content. - Flexible Sizing: Flex items can grow, shrink, or stay fixed based on the available space, using properties like
flex-grow,flex-shrink, andflex-basis. - Order Property: You can change the visual order of items without altering the HTML using the
orderproperty.
Example:
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
.item1 {
flex-grow: 2;
}
.item2 {
flex-grow: 1;
}
When to Use CSS Grid vs. Flexbox
- Use CSS Grid: When you need a complex layout with both rows and columns, such as a grid of cards, a dashboard, or a multi-column web page.
- Use Flexbox: When you need a simpler layout in a single direction, such as a navigation bar, a set of buttons, or aligning items in a single row or column.
Both systems can be used together for different parts of a web page to create complex and responsive layouts.