CSS Grid
CSS Grid lays out page elements in rows and columns. You can control their sizes and spacing, let the browser place items automatically, or make an item span multiple rows or columns.
What CSS Grid does
Imagine a photo gallery where every row uses the same column boundaries, but a featured photo takes up two columns. CSS Grid lets you define those shared boundaries once on the container and decide how individual items use the space. It's a two-dimensional layout system: rows and columns belong to the same grid.
Tracks, lines, and placement
Set display: grid on a container to make its direct, in-flow children grid items. A column or row is called a track, and the boundaries of the tracks are called lines. Use grid-template-columns and grid-template-rows to define tracks and gap to set the spacing between them.
Without placement rules, the browser normally fills the grid row by row. In a grid with three defined columns and no defined rows, the fourth item wraps into a second row. Both rows are implicit tracks: the browser creates them as needed, and you can control their size with grid-auto-rows. Tracks you define in advance are explicit.
For manual placement, grid-column: 1 / 3 puts an item between column lines 1 and 3, spanning two columns, not three. For larger layouts, grid-template-areas lets you name regions such as main and sidebar, then assign items to them with grid-area.
Example: a card grid that adapts to its container
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
gap: 1rem;
}
The browser fits as many columns as it can, allowing for the gap. Each column normally needs at least 16rem, but min(100%, 16rem) lets a single column fit a container narrower than that. If there are only two cards and room for three columns, auto-fit collapses the empty column. The two remaining 1fr tracks share the leftover space equally. No media query is needed to change the column count.
When to use Grid instead of Flexbox
Use Grid when items in different rows should line up on shared columns, as in a dashboard or product listing. Use Flexbox when the main job is to distribute items along a single axis, such as buttons in a toolbar. A flex container can wrap, but each flex line distributes its space independently. You can use both in one component: Grid for the cards and Flexbox for the controls inside each card.
One common mistake is treating visual placement as a substitute for meaningful HTML order. Moving a card to the top with Grid doesn't move it in the DOM, so keyboard focus and screen reader navigation may follow a different sequence from the visible layout.
What comes up in interviews
You may be asked to build a responsive gallery or explain why an extra row appeared. Be ready to identify which tracks you declared, which the browser generated, and what happens to empty columns when a wide container holds only a few items.