Media Queries
Overview
Before smartphones existed, websites were built with a static 960px width. When the iPhone released, websites were completely unreadable. Media Queries (@media) solved this by allowing developers to conditionally apply CSS rules only when the user's browser Window matches specific physical dimensions. This birthed 'Responsive Web Design'. The industry standard today is 'Mobile-First': you write your default CSS for tiny phone screens, and use min-width media queries to progressively enhance the layout as the screen gets wider.
Syntax
/* 1. Base Styles (MOBILE FIRST) */
/* These apply to every device, starting from an Apple Watch */
.container {
width: 100%;
padding: 10px;
}
/* 2. Tablet Breakpoint */
@media (min-width: 768px) {
.container {
padding: 20px;
}
}
/* 3. Desktop Breakpoint */
@media (min-width: 1024px) {
.container {
padding: 40px;
max-width: 1200px;
margin: 0 auto;
}
}
/* Modern Syntax (CSS Media Queries Level 4) */
/* Mathematically vastly cleaner than min/max width! */
@media (width >= 1024px) {
.sidebar { display: block; }
}Common Pitfalls
- Using
max-width(Desktop-First). If you style for Desktop first, and usemax-width: 768pxto 'fix' it for mobile, you force the mobile phone to download and parse a massive amount of desktop-specific CSS, overriding it milliseconds later. Mobile-first (min-width) is significantly faster and cleaner. - Creating arbitrary breakpoints (e.g.,
min-width: 632px) just to fix one broken button. Breakpoints should be standardized across your entire application (usually mapped to Tailwind's defaults: 640px, 768px, 1024px, 1280px).
Interview Questions
width >= 768px) exist to replace min-width?Readability and exactness. min-width and max-width are notoriously confusing to read quickly. Furthermore, combining them (min-width: 768px and max-width: 1024px) can cause fractional pixel bugs on scaled displays. 768px <= width <= 1024px is mathematically precise.
Real-World Example
Hiding a heavy background video on mobile devices to save battery and bandwidth.
.bg-video {
display: none; /* Mobile first: No video! */
}
/* Only load and display the video if the screen is large AND in landscape */
@media (min-width: 1024px) and (orientation: landscape) {
.bg-video {
display: block;
}
}Check Your Knowledge
Test your understanding of Media Queries with these quick questions.