Learn how CSS media queries enable responsive web design. Understand syntax, best practices, and practical examples for adaptable layouts.
Table of content
Responsive web design is essential in today’s multi-device world. CSS media queries are the core technique that allow developers to create layouts and styles that adapt to any screen size, from desktop monitors to tiny smartphones. Whether you’re a beginner or refreshing your knowledge, understanding media queries is crucial for modern web development.
Media queries are CSS rules that apply styles only if certain conditions about the device or viewport are met. They enhance your stylesheets by making your website adjust seamlessly to different devices.
@media (condition) {
/* CSS rules here */
}
The most common condition is max-width
or min-width
of the viewport.
.container {
width: 80%;
}
@media (max-width: 600px) {
.container {
width: 100%;
}
}
This changes the container to full width on screens up to 600px wide (e.g., most smartphones).
max-width
, min-width
, max-height
, min-height
orientation: landscape
or portrait
min-resolution
for targeting retina or high-DPI screensprefers-color-scheme
for dark/light mode@media (orientation: landscape) {
body {
background: #f5f5f5;
}
}
@media (min-resolution: 2dppx) {
.logo {
background-image: url('logo@2x.png');
}
}
min-width
to add desktop styles..menu {
display: block;
}
@media (min-width: 768px) {
.menu {
display: flex;
}
}
@media (min-width: 600px) and (orientation: landscape) {
.gallery {
grid-template-columns: repeat(4, 1fr);
}
}
You can combine multiple conditions for precise targeting.
CSS media queries are the foundation of responsive web design. Mastering their syntax and using them wisely allows you to deliver adaptable, user-friendly websites for everyone, everywhere.
Want to learn more? Check out MDN’s guide to media queries for in-depth resources and advanced examples.