CSS Media Queries
Media queries apply blocks of CSS only when conditions such as screen width are met, which is the core mechanism behind responsive design.
You write a base set of styles, then wrap overrides in an <code>@media</code> rule that activates at chosen screen widths, called breakpoints. The same page can then adapt its layout for phones, tablets, and desktops.
A Basic Media Query
Hide the sidebar on small screens
<!DOCTYPE html>
<html>
<head>
<style>
@media (max-width: 600px) {
.sidebar {
display: none;
}
}
</style>
</head>
<body>
<main>Main content</main>
<aside class="sidebar">Sidebar content</aside>
</body>
</html>Mobile-first With min-width
A common strategy is to style the mobile layout first, then use <code>min-width</code> queries to add enhancements for wider screens. This keeps the default styles lightweight for the smallest devices.
More padding on larger screens
<!DOCTYPE html>
<html>
<head>
<style>
.container {
padding: 16px;
}
@media (min-width: 768px) {
.container {
padding: 40px;
}
}
</style>
</head>
<body>
<div class="container">
<p>This container gets more padding on wider screens.</p>
</div>
</body>
</html>Common Features You Can Query
Stacking Columns On Mobile
Collapse a two-column grid
<!DOCTYPE html>
<html>
<head>
<style>
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
}
@media (max-width: 600px) {
.grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="grid">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
</div>
</body>
</html>Here a two-column grid collapses to a single column on narrow screens, a pattern you will use constantly when building a full website layout.
Exercise: CSS Media Queries
A media query with (min-width: 768px) applies its styles when the viewport is what?