Responsive Web Design with CSS
Learn responsive CSS basics: the viewport, flexible layouts, mobile-first media queries and practical breakpoints.
Set the viewport for mobile browsers
Include this metadata in the document head so the browser uses the device width as the page viewport. Without it, some mobile browsers may lay out the page on a wider virtual canvas and scale it down.
<meta name="viewport" content="width=device-width, initial-scale=1">
Start with a flexible layout
Responsive design lets a page adapt to the available space. Prefer flexible widths and wrapping before adding breakpoints for a specific device size.
.content {
width: min(100% - 2rem, 70rem);
margin-inline: auto;
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
gap: 1rem;
}
The minmax() and auto-fit combination lets the grid fit as many cards as the available space allows. Also make media elements flexible so a wide image or video cannot force the page to scroll sideways:
img,
video {
max-width: 100%;
height: auto;
}
Add a media query when the layout needs it
A media query applies styles only when its condition matches. A mobile-first stylesheet starts with the narrow layout, then adds changes as the viewport grows.
.site-nav {
display: grid;
gap: 0.5rem;
}
@media (min-width: 48rem) {
.site-nav {
display: flex;
align-items: center;
}
}
Choose breakpoints from the content
Resize the page and add a breakpoint where the content becomes crowded or difficult to use. Test text zoom and keyboard navigation as well as different screen widths.
Check for common responsive problems
- Fixed widths can overflow narrow screens. Use a maximum width with a flexible width, such as
width: min(100% - 2rem, 70rem). - Long words, URLs or code samples may stretch a column. Decide how those items should wrap or scroll instead of hiding the problem with page-wide overflow rules.
- Do not choose a breakpoint just because a device has a certain name. Add one when the current layout stops working well.
- Check the layout at intermediate widths too; a design can work on a phone and desktop but still break between them.
For more detail, see MDN's guide to media query fundamentals.