CSS

Responsive Stack to Row Layout with Flexbox

Transform a vertical stack of elements into a horizontal row on larger screens using Flexbox and a media query, creating adaptive layouts.

.responsive-container {
    display: flex;
    flex-direction: column; /* Default to stacked vertically */
    gap: 15px;
    padding: 20px;
    background-color: #f5f5f5;
}

.item {
    padding: 10px;
    background-color: #d0eaff;
    border: 1px solid #aaddff;
    text-align: center;
    width: 100%; /* Items take full width when stacked */
}

@media (min-width: 768px) {
    .responsive-container {
        flex-direction: row; /* Switch to horizontal on larger screens */
        justify-content: space-around; /* Distribute items */
    }
    .item {
        width: auto; /* Allow flex items to size naturally */
        flex-grow: 1; /* Optional: Make items grow to fill space */
    }
}
How it works: This snippet demonstrates how to create a responsive layout that stacks items vertically on small screens and arranges them horizontally on larger screens using Flexbox. The `.responsive-container` defaults to `flex-direction: column`. A media query then changes `flex-direction` to `row` for viewports wider than 768px, effectively transforming the layout from stacked to side-by-side.

Need help integrating this into your project?

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

Hire DigitalCodeLabs