Skip to main content

Responsive Layout

You've gathered some cool skills to create a great looking web application. But you've been creating for the device you work on. What happens when you run it on a phone? A tablet?

Responsive layout in CSS is about designing web pages that adapt gracefully to different screen sizes—from large desktops to tablets and small mobile phones. We have tools to produce one site that displays on any size device.

Flexbox and grid are great tools for responsive designs. But flexbox and grid alone don't discern the current device size to know whether a one-column, two-column or three-column layout is appropriate.

Media Queries

@media - Media queries allow us to customize the layout or styles at specific screen widths. We can modify our styles based on the viewport of the device screen width or device type.

@media (max-width: 800px) {
.sidebar {
display: none;
}
.main {
width: 80%;
}
}

@media (min-width: 30em) and (orientation: landscape) {
#container {
flex-direction: column;
justify-content: center;
}
}

Sample Responsive Layout

We can switch from a three-column layout to a stacked one-column layout (as normally seen on a phone) using CSS grid and a media query.

The HTML:

<div class="grid-container">
<div class="grid-item">Column 1</div>
<div class="grid-item">Column 2</div>
<div class="grid-item">Column 3</div>
</div>

and the CSS:

.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 1rem;
}

/* Mobile view: stack into one column */
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr;
}
}