@media rules in CSS allow you to apply styles conditionally based on device characteristics, such as screen size, orientation, or user preferences. They are the foundation of responsive web design, enabling your website to adapt seamlessly to mobiles, tablets, desktops, printers, and more.
Without @media, you'd write separate stylesheets for every device. With it, you create flexible, adaptive layouts in a single file.
The structure is simple:
@media media-type and (feature: value) {
/* Your CSS rules here */
}
Examples:
/* Mobile-first: Hide sidebar on small screens */
@media (max-width: 768px) {
.sidebar { display: none; }
}
Specify the device or output:
| Type | Description |
|---|---|
all | Default: All devices |
screen | Screens (phones, laptops) |
print | Printers |
speech | Screen readers |
@media print {
.no-print { display: none; }
body { font-family: serif; }
}
min-width, max-widthportrait or landscapemin-resolution: 192dpi (for Retina)/* Tablet landscape */
@media (min-width: 768px) and (orientation: landscape) {
.container { display: flex; }
}
Support user preferences and accessibility:
/* Dark mode */
@media (prefers-color-scheme: dark) {
body { background: #121212; color: #eee; }
}
/* Reduced motion for accessibility */
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; }
}
/* Hover support (mouse) */
@media (hover: hover) {
.card:hover { transform: scale(1.05); }
}
/* Touch devices */
@media (pointer: coarse) {
button { min-height: 44px; padding: 1rem; }
}
Use and, or, not:
@media screen and (min-width: 600px) and (max-width: 900px),
print and (orientation: portrait) {
/* Multiple conditions */
}
To make creating these queries effortless, I've built a 100% Vanilla JS/HTML/CSS Generator. It's a split-panel tool:
<textarea>.No libraries, no setup-just copy/paste to your project. Perfect for beginners and pros!
screen or print).min-width/max-width and set pixels.
Pro Tip: Combine multiple options for complex queries like @media screen and (max-width: 768px) and (orientation: portrait).
@media screen and (min-width: 1024px) {
/* Your styles here */
.container { background: lightblue; }
}
@media (prefers-color-scheme: dark) {
/* Dark mode */
body { background: #121212; color: #eee; }
}
Master @media and build responsive sites in minutes. Use generator today and experiment!