π What is @media?
@media is a CSS at-rule used to apply styles only when certain conditions (like screen width, orientation, resolution, or device type) are met. It is the core of responsive design, enabling layouts to adapt to different screens.
π― Why Use @media?
- π± Adjust layout for different screen sizes
- π» Improve readability on large displays
- π Make designs mobile-friendly
- βοΈ Apply conditional styling for orientation or dark mode
- π₯οΈ Optimize spacing, font sizes, and grids across breakpoints
π Basic Syntax
Basic @media Syntax
@media (condition) {
/* CSS rules here */
}π― Most Common Type β Width-Based Media Queries
π Max-width (Mobile-first responsive design)
max-width Example
@media (max-width: 768px) {
.card {
padding: 10px;
font-size: 14px;
}
}Styles apply when the screen width is **768px or below**.
π Min-width (Progressive enhancement)
min-width Example
@media (min-width: 1024px) {
.container {
max-width: 1200px;
padding: 40px;
}
}Styles apply when width is **1024px or above** β perfect for desktop enhancements.
π Common Breakpoints (Industry Standard)
| Device Type | Breakpoint |
|---|---|
| Mobile | max-width: 480px |
| Small Tablets | max-width: 768px |
| Large Tablets | max-width: 1024px |
| Laptops | min-width: 1200px |
Note
π§ Combining Conditions
π Width + Orientation
Orientation Example
@media (max-width: 768px) and (orientation: landscape) {
.banner {
height: 200px;
}
}π Dark Mode Detection
Dark Mode Media Query
@media (prefers-color-scheme: dark) {
body {
background: #111;
color: #eee;
}
}π High-Resolution Displays (Retina Screens)
High DPI Example
@media (min-resolution: 2dppx) {
.logo {
background-image: url("logo@2x.png");
}
}π§ͺ Practical Example β Responsive Navigation
Responsive Navbar
.nav {
display: flex;
gap: 20px;
}
@media (max-width: 600px) {
.nav {
flex-direction: column;
gap: 10px;
}
}Navbar switches from horizontal β vertical layout on mobile screens.
π₯ Practical Example β Responsive Grid
Responsive Grid with @media
.gallery {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
}
@media (max-width: 900px) {
.gallery {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 600px) {
.gallery {
grid-template-columns: 1fr;
}
}Grids shrink from 4 β 2 β 1 column based on device size.
π± Mobile-First vs Desktop-First
| Approach | Uses | Query Type |
|---|---|---|
| Mobile-First | Start small, scale up | min-width |
| Desktop-First | Start large, scale down | max-width |
Note
β οΈ Common Mistakes
- Using too many breakpoints β keep it simple
- Using device-specific widths like 375px or 414px
- Not testing on real devices or simulators
- Writing contradictory min-width & max-width rules
- Forgetting that @media applies after base styles
π₯ Summary
@media is the foundation of responsive design. By controlling styles based on screen size, orientation, resolution, and preferences, you can build interfaces that look great everywhere.
Learn more βMDN Docs π