Media queries are conditional CSS rules that apply styles based on device characteristics such as screen size, resolution, or orientation. They are the foundation of responsive web design, allowing content to adapt to various devices and viewports.
What are media queries and why are they used?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
Media queries enable developers to define different styles depending on the device’s capabilities. This allows webpages to look and function optimally across desktops, tablets, and smartphones, forming the backbone of responsive design.
Feature | Example | Purpose |
|---|---|---|
min-width | @media (min-width: 768px) | Applies when the viewport is at least 768px wide. |
max-width | @media (max-width: 600px) | Applies when the viewport is 600px wide or less. |
orientation | @media (orientation: landscape) | Applies styles for landscape or portrait mode. |
resolution | @media (min-resolution: 300dpi) | Targets high-resolution (Retina) displays. |
Example: Responsive Layout
body {
font-size: 16px;
}
@media (max-width: 768px) {
body {
font-size: 14px;
}
}
@media (max-width: 480px) {
body {
font-size: 12px;
}
}
This example adjusts the text size for tablets and mobile screens, improving readability on smaller devices.
Combining Conditions
Media queries can combine multiple conditions using logical operators:
and– combine features (@media (min-width: 600px) and (orientation: landscape)).not– exclude specific conditions.only– prevent older browsers from applying the rule.
Mobile-First Approach
Modern best practice is to start with default (mobile) styles and add media queries for larger viewports. This ensures faster rendering and fewer overrides:@media (min-width: 768px) { /* tablet styles */ }@media (min-width: 1024px) { /* desktop styles */ }
Advanced Features
- Media queries support prefers-color-scheme for dark/light mode.
- prefers-reduced-motion helps accessibility by disabling animations for users who prefer reduced motion.
- Container queries (in modern browsers) extend this concept to parent element widths rather than the viewport.
Think of media queries as smart CSS switches — they turn on or off specific styles depending on the screen’s size or features, just like adaptive headlights adjusting to road conditions.
- Media queries adapt designs to different screen sizes and device capabilities.
- Essential for responsive design and accessibility.
- Support conditions like width, orientation, resolution, and user preferences.
- Combine with a mobile-first strategy for performance and scalability.