How to Use max-width Media Query in CSS for Responsive Design
Use the
@media (max-width: value) rule in CSS to apply styles only when the viewport width is less than or equal to the specified value. This helps create responsive designs that adapt to smaller screens like phones or tablets.Syntax
The @media rule with max-width applies CSS styles when the viewport width is at or below a certain size.
@media: starts the media query.(max-width: value): condition for maximum viewport width (e.g., 600px).- Curly braces
{ }: contain the CSS rules to apply.
css
@media (max-width: 600px) { /* CSS rules here */ }
Example
This example changes the background color and font size of a paragraph when the screen width is 600px or less.
css
p {
background-color: lightblue;
font-size: 1.5rem;
padding: 1rem;
}
@media (max-width: 600px) {
p {
background-color: lightcoral;
font-size: 1rem;
}
}Output
A paragraph with a light blue background and larger text on wide screens. On screens 600px wide or smaller, the background changes to light coral and the text becomes smaller.
Common Pitfalls
- Using
max-widthwithout units (likepx) causes the media query to fail. - Placing media queries inside other selectors instead of at the root level can prevent them from working.
- Overlapping media queries without clear order can cause unexpected style conflicts.
css
/* Wrong: missing units */ @media (max-width: 600) { body { background: red; } } /* Right: with units */ @media (max-width: 600px) { body { background: red; } }
Quick Reference
Use max-width media queries to target devices with screen widths up to a certain size. Combine with min-width for ranges. Always include units like px or em. Place media queries at the end of your CSS for proper overriding.
Key Takeaways
Use
@media (max-width: value) to apply styles on screens up to that width.Always include units like
px or em with max-width values.Place media queries at the root level and at the end of your CSS for proper effect.
Test your design on different screen sizes to ensure responsiveness.
Combine max-width with min-width for precise control over style ranges.