How to Use min-width Media Query in CSS for Responsive Design
Use the
@media (min-width: value) rule in CSS to apply styles only when the viewport width is equal to or greater than the specified value. This helps create responsive designs that adjust layout or styling on larger screens.Syntax
The @media rule with min-width applies CSS styles when the viewport width is at least the specified value. The value is usually in pixels (px), but can also use other units like em or rem.
- @media: starts the media query
- (min-width: value): condition that checks if viewport width is at least
value - { ... }: CSS rules inside apply only if condition is true
css
@media (min-width: 600px) { /* CSS rules here */ }
Example
This example changes the background color of a box when the screen width is 600 pixels or wider. Resize the browser window to see the color change.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>min-width Media Query Example</title> <style> .box { width: 200px; height: 200px; background-color: lightcoral; transition: background-color 0.3s ease; } @media (min-width: 600px) { .box { background-color: lightseagreen; } } </style> </head> <body> <div class="box"></div> </body> </html>
Output
A square box 200px by 200px with a light coral background that changes to light sea green when the browser width is 600px or wider.
Common Pitfalls
Common mistakes when using min-width media queries include:
- Using
max-widthwhen you meanmin-width, which targets smaller screens instead of larger. - Not including the
@mediarule properly, causing styles to always apply. - Forgetting to set the viewport meta tag in HTML, which can make media queries behave unexpectedly on mobile devices.
css
@media (max-width: 600px) { /* This targets screens smaller than 600px, not larger */ } /* Correct usage for larger screens: */ @media (min-width: 600px) { /* Styles for screens 600px and wider */ }
Quick Reference
Tips for using min-width media queries effectively:
- Use
min-widthto create "mobile-first" responsive designs that add styles as screen size grows. - Combine multiple media queries for different breakpoints to adjust layout progressively.
- Always include
<meta name="viewport" content="width=device-width, initial-scale=1">in your HTML for proper scaling on mobile. - Test your design by resizing the browser or using device simulation in browser DevTools.
Key Takeaways
Use @media (min-width: value) to apply CSS only on screens at least that wide.
Min-width queries help build mobile-first responsive designs that adapt to larger screens.
Always include the viewport meta tag in HTML for media queries to work correctly on mobile.
Test media queries by resizing your browser or using device simulation tools.
Avoid confusing min-width with max-width to target the correct screen sizes.