By the end of this lesson, you will be able to write CSS media queries that adapt layout and typography based on screen size, ensuring your website looks good on both mobile devices and desktop monitors.
What it is
A media query is a CSS feature that allows you to apply styles only when specific conditions are met. The most common condition is the viewport width, but you can also check for device orientation, resolution, or color scheme. Think of media queries as "if-then" statements for your design: If the screen is wider than 768 pixels, then use these specific styles.
Key terms include:
- Viewport: The visible area of the web page in the browser window.
- Breakpoint: A specific pixel value where the layout changes (e.g., switching from one column to two).
- Media Feature: The characteristic being tested, such as
min-width,max-width, ororientation.
Why it matters
- Responsiveness: Ensures content remains readable and usable across phones, tablets, laptops, and large monitors.
- User Experience: Prevents horizontal scrolling on small screens and optimizes touch targets for mobile users.
- Maintenance: Keeps all styling logic within CSS files rather than relying on JavaScript for basic layout shifts.
- Performance: Allows you to load different background images or font sizes appropriate for the device capabilities.
Syntax or steps
The basic syntax wraps existing CSS rules inside an @media block. You define the media type (usually omitted for modern browsers) and the feature to test.
@media (feature: value) {
/* CSS rules applied only if condition is true */
}
Common features include:
(min-width: 768px): Applies styles when the viewport is 768px or wider.(max-width: 767px): Applies styles when the viewport is 767px or narrower.(orientation: landscape): Applies styles when the device is rotated horizontally.
Example
This example demonstrates a simple responsive grid. On small screens, columns take up full width. On medium screens (tablets), they split into two columns. On large screens (desktops), they become three columns.
/* Base styles for mobile-first approach */
.container {
display: flex;
flex-wrap: wrap;
}
.col {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
/* Tablet breakpoint */
@media (min-width: 768px) {
.col {
width: 50%;
}
}
/* Desktop breakpoint */
@media (min-width: 1024px) {
.col {
width: 33.33%;
}
}
Explanation:
- Base Styles: We start with
.col { width: 100%; }. This ensures the default view works on the smallest devices without needing extra code. - First Query: When the screen hits 768px, the rule inside
@media (min-width: 768px)overrides the base style, setting width to 50%. - Second Query: When the screen hits 1024px, the next rule takes precedence, narrowing columns to roughly one-third width.
Common mistakes
- Forgetting the Meta Viewport Tag: Without
<meta name="viewport" content="width=device-width, initial-scale=1">in your HTML head, mobile browsers will pretend to be desktops, ignoring your media queries. - Using Pixels for Font Sizes: While okay for breakpoints, using fixed pixels for text prevents user zooming. Use
remoremfor typography instead. - Conflicting Specificity: If a base rule has higher specificity than a media query rule, the media query might not apply. Ensure your selectors match exactly.
- Too Many Breakpoints: Creating custom breakpoints for every possible device leads to messy code. Stick to standard ranges (mobile, tablet, desktop) unless necessary.
When to use it
Compare media queries with Flexbox/Grid auto-layouts:
| Feature | Media Queries | CSS Grid/Flexbox Auto-fit |
|---|---|---|
| Control | Precise control over exact widths and styles. | Layout adapts automatically based on available space. |
| Complexity | Higher; requires managing multiple breakpoints. | Lower; often requires fewer lines of code. |
| Best For | Changing typography, hiding elements, or major layout shifts. | Card grids, image galleries, and uniform spacing. |
Use media queries when you need to change what is displayed or significantly alter structure. Use Grid/Flexbox properties like auto-fit when you just want items to flow naturally.
Practice
Guided Exercise: Create a navigation bar that stacks vertically on mobile (flex-direction: column) and aligns horizontally on screens wider than 600px (flex-direction: row).
Challenge: Add a dark mode toggle using @media (prefers-color-scheme: dark) that changes the body background to black and text to white.
Hint: Place the dark mode rules after your base light mode rules so they override correctly.
Quick check
Question: Why is the "mobile-first" approach recommended when writing media queries?
Answer: It simplifies CSS by defining base styles for small screens first, then adding complexity via min-width queries for larger screens, reducing the need for overriding conflicting rules.
Summary
Media queries enable responsive design by applying conditional CSS based on device characteristics like viewport width. By adopting a mobile-first strategy and using standard breakpoints, you ensure consistent usability across all devices while maintaining clean, manageable code.