Media Queries

The modern web is accessed on everything from tiny watches and smartphones to massive 4K monitors and even printers. Responsive Design is the practice of making your website look great on all of them. The secret weapon behind this flexibility is the Media Query.

A Media Query allows you to apply CSS rules only when certain conditions are met, such as the screen being wider than 600 pixels or the device being in "landscape" mode.

1. Media Types

Before we look at screen sizes, we need to define the Media Type. This tells the browser which kind of device the CSS is for.

Media Types
Media TypeDescription
allMatches all devices (Default)
printApplied when the user tries to print the page
screenUsed for smartphones, tablets, and computer screens
speechUsed for screen readers that "read" the page aloud

Example: Loading CSS by Media Type

You can load specific files directly in your HTML or via CSS imports:

Code Block Loading...

Code Block Loading...

2. Media Feature Descriptors

Descriptors are the specific conditions we test for. These allow us to get very granular with our responsive rules.

Common descriptors include width, height, orientation, and resolution. Most of these support min- and max- prefixes (e.g., max-width).

Interactive Orientation Demo

The orientation feature detects if a device is held vertically (portrait) or horizontally (landscape).

Code Block Loading...

3. Logical Operators: And, Or, Not

You can combine multiple conditions using logic:

  1. and: All conditions must be true.
  2. , (Comma): Acts as an OR if any condition is true, the CSS applies.
  3. not: Negates the entire query.

CSS Example (The "And" Logic):

Code Block Loading...

4. Using @media in CSS

The most powerful way to use media queries is directly inside your stylesheet. This allows you to keep all your code in one file while defining different layouts for different screens.

Interactive Responsive Breakpoint Demo

Resize the window to see how the "Breakpoint" affects the layout.

Code Block Loading...

Key Takeaways

  • Mobile-First Design: It is a best practice to write your default CSS for mobile phones and then use @media (min-width: ...) to add complexity for larger screens.
  • Logical Combinations: Use and to target specific ranges and commas (,) to target multiple distinct media types.
  • The Default: screen is the most commonly used media type, but don't forget print for documents or resumes.
  • Viewport Matters: Always include the <meta name="viewport" content="width=device-width, initial-scale=1"> tag in your HTML <head> for media queries to work correctly on mobile devices.