Why Media Queries are Needed in CSS
Media queries are a mechanism in CSS that allows applying styles depending on device characteristics, such as screen width, pixel density, orientation, etc.
Why are Media Queries Needed?
Media queries allow creating responsive and cross-device interfaces that look good on:
- Smartphones
- Tablets
- Laptops
- Monitors with different resolutions
Goal:
Make the site work and look equally good on different screens — from iPhone to 4K monitor.
Simple Example
/* Base style */
.container {
padding: 20px;
}
/* Applied when screen width is less than 768px */
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
Typical Use Cases
- Adapting fonts and margins for different screens
- Hiding or showing mobile menu
- Restructuring grids and flex containers
- Changing image or card sizes
- Handling dark/light theme via
(prefers-color-scheme)
Types of Media Features
| Property | What it checks |
|---|---|
width / height | Screen/viewport size |
max-width / min-width | Maximum or minimum width |
orientation | Screen orientation (portrait/landscape) |
resolution | Pixel density |
prefers-color-scheme | System theme (dark / light) |
Responsive Grid Example
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
@media (max-width: 1024px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 640px) {
.grid {
grid-template-columns: 1fr;
}
}
This way, grid restructures for screen size: 3 → 2 → 1 column.
Mobile-First Strategy
Most often styles are written first for mobile devices, then media queries with min-width are added for wider screens:
.button {
font-size: 14px;
}
@media (min-width: 768px) {
.button {
font-size: 16px;
}
}
Summary
- Media queries — key to responsive layout
- Allow applying different styles depending on device, screen and user settings
- Help improve usability and site appearance on all devices
Conclusion:
If you're making a site for users who will access from different devices — media queries are mandatory.