@media is a CSS rule that applies different styles based on device characteristics (screen size, orientation, resolution, etc.) — the foundation of responsive web design.
What use???
@media applies CSS styles only when certain conditions are met
It checks: screen width, height, orientation, resolution, device type
Core technology for responsive web design (RWD)
Why use???
Different screen sizes:Mobile, tablet, desktop need different layouts.
Better UX:Content adapts to device for better user experience.
Print vs Screen: Different styles for printing vs displaying on screen
When use???
Use @media when:
Screen width changes — e.g., mobile (< 600px), tablet (600-900px), desktop (> 900px).
Orientation changes — portrait vs landscape.
Device type — screen, print, speech (screen readers).
User preferences — reduced motion, dark mode, data usage.
How to Use???
Basic Syntax:
@media media-type and (media-feature: value) {
/* CSS rules */
}
Common Examples:
1. Mobile First: (screen width ≤ 600px)
/* Default (mobile) */
.container
{
width: 100%;
padding: 10px;
}
/* Tablet and Desktop */
@media (min-width: 600px)
{
.container {
width: 540px;
padding: 20px;
}
}
/* Large Desktop */
@media (min-width: 900px)
{
.container {
width: 720px;
}
}
2. Orientation (Portrait vs Landscape):
/* Portrait mode */
@media (orientation: portrait)
{
.image
{
width: 100%;
}
}
/* Landscape mode */
@media (orientation: landscape)
{
.image
{
width: 50%;
}
}
3. Print Styles:
@media print {
.no-print {
display: none;
}
body {
font-size: 12pt;
}
}
4. Multiple Conditions:
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* Applies to tablets only */
.grid {
columns: 2;
}
}
Quick Reference Table:
| Media Feature | Example | What it checks |
|---|---|---|
| min-width | @media (min-width: 600px) |
Screen width ≥ 600px |
| max-width | @media (max-width: 768px) |
Screen width ≤ 768px |
| orientation | @media (orientation: portrait) |
Portrait or landscape mode |
| resolution | @media (resolution: 2dppx) |
Screen resolution (retina displays) |
@media print |
When printing document | |
| prefers-reduced-motion | @media (prefers-reduced-motion: reduce) |
User wants less animation |
Complete Working Example:
<!DOCTYPE html>
<html>
<head>
<style>
.body {
background: lightblue; /* Default (mobile) */
}
/* Tablet */
@media (min-width: 600px) {
.body {
background: lightgreen;
}
}
/* Desktop */
@media (min-width: 900px) {
.body {
background: lightcoral;
}
}
</style>
</head>
<body>
<div class="body">Resize browser to see color change!</div>
</body>
</html>
Background color changes based on screen width.
@media lets your website adapt to different devices automatically, making it responsive and user-friendly across phones, tablets, and desktops.
Top comments (0)