CSS Media Queries: Responsive Web
The web isn't just viewed on 1080p desktop monitors anymore. Your users are on phones, tablets, smart TVs, and everything in between. Media Queries are the magic that makes your website fluid, adaptable, and beautiful on every screen size.
The Viewport Meta Tag
Before you even write a single media query, you must tell mobile browsers not to pretend to be a desktop. Add this inside your HTML <head>:
<meta name="viewport" content="width=device-width, initial-scale=1.0">Without it, a mobile phone will render your site at ~980px width and zoom out, making your text unreadable and rendering your media queries useless.
Anatomy of a Media Query
A media query consists of an optional media type (like screen or print) and any number of media feature expressions (like min-width).
@media screen and (min-width: 768px) {
/* CSS rules apply when screen is 768px or wider */
.container { display: flex; }
}The "Mobile-First" Philosophy
Instead of styling for desktop and using max-width to squish things down for mobile, industry best practice is Mobile-First.
- Write your base styles for the smallest screens outside of any media queries.
- Use
min-widthmedia queries to add layout complexity as the screen gets wider. - This results in less code overriding, faster rendering on weak mobile devices, and fewer bugs.
❓ Frequently Asked Questions
¿Cuál es la diferencia entre min-width y max-width?
min-width: "A partir de este ancho hacia arriba". Si usas (min-width: 768px), el código se aplica en pantallas de 768px, 1024px, 1920px... (Desktop-first).
max-width: "Desde este ancho hacia abajo". Si usas (max-width: 767px), el código se aplica en pantallas de 767px, 320px... (Diseño para móviles cuando usas enfoque desktop-first).
¿Cuáles son los breakpoints más comunes?
Aunque la filosofía ideal es poner breakpoints donde el diseño se rompe, los estándares habituales de la industria (como Tailwind) son:
- 640px: Móviles grandes / Tablets pequeñas (sm)
- 768px: Tablets en vertical (md)
- 1024px: Tablets en horizontal / Portátiles (lg)
- 1280px: Escritorio normal (xl)
¿Puedo combinar múltiples condiciones?
¡Sí! Usa la palabra clave and para requerir múltiples condiciones, o una coma , (que actúa como un OR).
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* Aplica solo a tablets específicas */
}