Grid and Flexbox are both powerful layout systems in CSS, each designed for different types of layout tasks. Here's a comparison of the two, along with examples to illustrate their differences:
Purpose:
Flexbox is designed for one-dimensional layouts. It handles alignment and spacing of items along a single axis (either row or column).
Key Features:
Example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Example</title> <style> .container { display: flex; justify-content: space-between; /* Distributes space between items */ align-items: center; /* Aligns items vertically in the center */ height: 100vh; background-color: lightgrey; } .item { background-color: dodgerblue; color: white; padding: 20px; text-align: center; flex: 1; /* Makes items flexible */ margin: 10px; } </style> </head> <body> <div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div> </body> </html>
Features Illustrated:
Purpose:
Grid is designed for two-dimensional layouts. It handles both rows and columns simultaneously, allowing for complex layouts.
Key Features:
Example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Grid Example</title> <style> .container { display: grid; grid-template-columns: repeat(3, 1fr); /* Creates three equal-width columns */ grid-gap: 10px; /* Adds space between grid items */ height: 100vh; background-color: lightgrey; } .item { background-color: dodgerblue; color: white; padding: 20px; text-align: center; } .item:nth-child(2) { grid-column: span 2; /* Makes the second item span two columns */ } </style> </head> <body> <div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div> </body> </html>
Features Illustrated:
Choosing between Flexbox and Grid depends on the complexity of your layout and whether you need one-dimensional or two-dimensional control. Often, both can be used together to achieve the desired layout.
The above is the detailed content of Grid and Flexbox. For more information, please follow other related articles on the PHP Chinese website!