What is mediaquery?
A media query is a CSS feature that lets you apply different styles to a webpage depending on characteristics of the device displaying it, such as screen width, height, orientation, resolution, or even light/dark mode. It works like an “if‑statement” for styling: if the device matches the conditions you set, the CSS inside the query is used.
Let's break it down
- Media type - tells what kind of device you’re targeting (e.g., screen, print, speech). Most often we use “screen”.
- Media feature - a specific property to test, like
max-width
,orientation
,resolution
, etc. - Expression - combines a feature with a value, e.g.,
(max-width: 600px)
. - Rule block - the CSS rules that run when the expression is true. Example:
@media screen and (max-width: 600px) {
body { font-size: 14px; }
}
When the viewport is 600 px wide or less, the body text becomes 14 px.
Why does it matter?
Media queries make websites responsive - they adapt to phones, tablets, laptops, and large monitors without needing separate pages. This improves user experience, keeps visitors longer, and helps with SEO because search engines favor mobile‑friendly sites. It also reduces the need for duplicate code, saving development time.
Where is it used?
- In CSS files or
<style>
tags of any website. - Inside component libraries (e.g., React, Vue) to change layout based on screen size.
- In CSS frameworks like Bootstrap, Tailwind, or Foundation, which ship pre‑written media queries.
- In progressive web apps (PWAs) to adjust UI for different device capabilities.
- In print stylesheets to format pages differently when printed.
Good things about it
- Flexibility - target many device traits, not just width.
- Performance - browsers only apply the relevant rules, avoiding unnecessary CSS.
- Maintainability - keep all styles in one stylesheet; no need for separate mobile/desktop files.
- Standardized - supported by all modern browsers and part of the official CSS spec.
- Future‑proof - new features (e.g.,
prefers‑color‑scheme
) can be added without changing HTML.
Not-so-good things
- Complexity - many breakpoints can make the stylesheet hard to read if not organized.
- Testing overhead - you must check the design on multiple screen sizes and orientations.
- Limited to CSS - cannot change HTML structure; sometimes you need JavaScript for deeper layout changes.
- Older browsers - very old browsers (IE 8 and earlier) have limited or no support for media queries.