How to Use Media Query in CSS for Responsive Design
Use
@media in CSS to apply styles only when certain conditions like screen width are met. This helps make your website look good on phones, tablets, and desktops by changing styles based on device features.Syntax
The @media rule starts a media query block. Inside parentheses, you specify conditions like max-width or min-width. Then, inside curly braces, you write CSS rules that apply only if the conditions are true.
Example parts:
@media: starts the media query(max-width: 600px): condition for screen width 600 pixels or less{ ... }: CSS rules to apply when condition matches
css
@media (max-width: 600px) { /* CSS rules here */ }
Example
This example changes the background color and text size when the screen width is 600 pixels or less. Resize your browser window to see the effect.
css
body {
background-color: lightblue;
font-size: 18px;
}
@media (max-width: 600px) {
body {
background-color: lightcoral;
font-size: 14px;
}
}Output
A page with a light blue background and large text on wide screens, changing to a light coral background and smaller text on narrow screens (600px or less).
Common Pitfalls
Common mistakes include:
- Forgetting to use parentheses around conditions.
- Using
max-widthandmin-widthincorrectly, causing styles not to apply as expected. - Placing media queries inside other CSS rules instead of at the top level.
- Not testing on different screen sizes or devices.
Always check your syntax and test by resizing your browser or using device simulators.
css
@media max-width: 600px { /* Wrong: missing parentheses */ body { background-color: red; } } /* Correct syntax: */ @media (max-width: 600px) { body { background-color: red; } }
Quick Reference
| Media Feature | Description | Example |
|---|---|---|
| max-width | Applies styles if screen width is less than or equal to value | @media (max-width: 600px) { ... } |
| min-width | Applies styles if screen width is greater than or equal to value | @media (min-width: 601px) { ... } |
| orientation | Applies styles based on device orientation | @media (orientation: portrait) { ... } |
| prefers-color-scheme | Detects if user prefers dark or light mode | @media (prefers-color-scheme: dark) { ... } |
Key Takeaways
Use @media with conditions in parentheses to apply CSS only on certain screen sizes or features.
Test media queries by resizing your browser or using device simulators to ensure styles apply correctly.
Common errors include missing parentheses and incorrect use of max-width/min-width.
Media queries help create responsive designs that adapt to phones, tablets, and desktops.
Combine multiple conditions with 'and' for more precise control over styles.