CSS

CSS Grid: Responsive Item Reordering

Learn to easily change the visual order of individual grid items on different screen sizes using CSS Grid's placement properties for responsive designs.

.grid-container {
    display: grid;
    grid-template-columns: 1fr; /* Single column on mobile */
    gap: 1rem;
    padding: 1rem;
    border: 1px dashed #ccc;
}

.grid-item {
    padding: 1.5rem;
    background-color: #f0f8ff;
    border: 1px solid #add8e6;
    text-align: center;
    font-weight: bold;
}

/* Default mobile order: Item 1, Item 2, Item 3, Item 4 */

@media (min-width: 768px) {
    .grid-container {
        grid-template-columns: repeat(2, 1fr); /* Two columns on desktop */
    }

    /* Desktop order: Item 1 (top-left), Item 3 (top-right), Item 2 (bottom-left), Item 4 (bottom-right) */
    .item-1 { grid-column: 1 / 2; grid-row: 1 / 2; }
    .item-2 { grid-column: 1 / 2; grid-row: 2 / 3; }
    .item-3 { grid-column: 2 / 3; grid-row: 1 / 2; }
    .item-4 { grid-column: 2 / 3; grid-row: 2 / 3; }
}
How it works: This snippet demonstrates how to reorder individual items within a CSS Grid layout responsively. On mobile, items stack in their source order within a single column. For wider screens, a media query changes the grid to two columns. Crucially, the `grid-column` and `grid-row` properties are used on individual items to explicitly place them in a new visual order, for example, moving 'Item 2' to the bottom-left and 'Item 3' to the top-right.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs