Grid and Flexbox help arrange things on a webpage neatly. They make layouts easy and flexible without messy code.
Grid vs flexbox in CSS
/* Flexbox container */ display: flex; /* Grid container */ display: grid;
Flexbox works mainly in one direction: row or column.
Grid works in two directions: rows and columns together.
/* Flexbox example */ .container { display: flex; flex-direction: row; justify-content: center; align-items: center; }
/* Grid example */ .container { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }
This page shows two sections: one uses Flexbox to arrange three boxes in a row with space around them. The other uses Grid to create three equal columns with boxes inside. Both have borders and spacing so you can see the difference clearly.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Grid vs Flexbox Example</title> <style> body { font-family: Arial, sans-serif; margin: 2rem; } h2 { margin-bottom: 0.5rem; } .flex-container { display: flex; flex-direction: row; justify-content: space-around; align-items: center; border: 2px solid #4a90e2; padding: 1rem; margin-bottom: 2rem; gap: 1rem; } .grid-container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; border: 2px solid #e24a4a; padding: 1rem; } .box { background-color: #f0f0f0; border: 1px solid #ccc; padding: 1rem; text-align: center; font-weight: bold; user-select: none; } </style> </head> <body> <section> <h2>Flexbox Layout</h2> <div class="flex-container" role="list"> <div class="box" role="listitem">Item 1</div> <div class="box" role="listitem">Item 2</div> <div class="box" role="listitem">Item 3</div> </div> </section> <section> <h2>Grid Layout</h2> <div class="grid-container" role="list"> <div class="box" role="listitem">Item A</div> <div class="box" role="listitem">Item B</div> <div class="box" role="listitem">Item C</div> </div> </section> </body> </html>
Flexbox is great for simple layouts in one direction, like menus or toolbars.
Grid is better for complex layouts with rows and columns, like entire pages or galleries.
Both work well on small screens and can be combined for powerful designs.
Flexbox arranges items in a row or column, good for simple linear layouts.
Grid arranges items in rows and columns, good for complex layouts.
Use the right tool depending on how you want your content arranged.