Media queries help your website look good on all devices by changing styles based on screen size or device features.
0
0
Media queries in CSS
Introduction
You want your website text to be bigger on small phones for easy reading.
You want to hide a sidebar on small screens to save space.
You want to change the layout from columns to rows on tablets.
You want to adjust colors or fonts depending on light or dark mode.
You want images to resize automatically on different screen widths.
Syntax
CSS
@media (condition) { /* CSS rules here */ }
The
condition can check screen width, height, orientation, and more.You can combine conditions with
and and not.Examples
This changes the background color to light blue on screens 600px wide or smaller.
CSS
@media (max-width: 600px) { body { background-color: lightblue; } }
This sets a bigger font size on medium screens between 601px and 1024px wide.
CSS
@media (min-width: 601px) and (max-width: 1024px) { body { font-size: 1.2rem; } }
This hides the navigation menu when the device is held vertically (portrait mode).
CSS
@media (orientation: portrait) { nav { display: none; } }
Sample Program
This page uses a media query to change background color and text size when the screen is 600px wide or smaller. Try resizing your browser window to see the effect.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Media Queries Example</title> <style> body { font-family: Arial, sans-serif; background-color: white; color: black; margin: 2rem; } h1 { font-size: 2rem; } p { font-size: 1rem; } /* Change background and text on small screens */ @media (max-width: 600px) { body { background-color: #f0f8ff; color: #003366; } h1 { font-size: 1.5rem; } p { font-size: 1.2rem; } } </style> </head> <body> <h1>Welcome to My Website</h1> <p>Resize the browser window to see the background and text size change on small screens.</p> </body> </html>
OutputSuccess
Important Notes
Always include the viewport meta tag in your HTML to make media queries work well on mobile devices.
Test your site on different devices or use browser DevTools to simulate screen sizes.
You can combine multiple media queries for more control over your design.
Summary
Media queries let your website adapt to different screen sizes and device features.
Use them to improve readability and usability on phones, tablets, and desktops.
They are written inside CSS with the @media rule and conditions like max-width.