Performance: Grid vs flexbox
This affects how the browser calculates layout and paints elements, impacting page load speed and responsiveness.
Jump into concepts and practice - no test required
display: flex; flex-direction: row; justify-content: space-between;
display: grid; grid-template-columns: repeat(5, 1fr);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Flexbox for simple row | Low DOM depth | 1 reflow | Low paint | [OK] Good |
| Grid for simple row | Low DOM depth | 2 reflows | Medium paint | [!] OK |
| Flexbox for complex grid | Medium DOM depth | Multiple reflows | High paint | [X] Bad |
| Grid for complex grid | Medium DOM depth | Few reflows | Medium paint | [OK] Good |
display: flex;.display: grid; creates a grid container, not flex. flex-direction: grid; is invalid. flex-container: true; is not a valid CSS property..container?
.container {
display: flex;
flex-direction: column;
gap: 1rem;
}
.item {
width: 100px;
height: 50px;
background-color: lightblue;
}display: flex; and flex-direction: column;, so items stack vertically.gap: 1rem; adds space between items vertically in column direction..grid-container {
display: flex;
grid-template-columns: repeat(3, 1fr);
}display: flex;, which does not support grid-template-columns.grid-template-columns works only with display: grid;. Mixing flex display with grid properties causes no effect or errors..gallery {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.photo {
flex: 1 1 200px;
height: 150px;
}
Why might CSS Grid be a better choice here?