tezvyn:

Media Queries: CSS That Adapts to the User's Device

AI-drafted, machine-checkedSource: w3.orgadvanced

Instead of one-size-fits-all CSS, media queries let your styles react to the user's device. They are used to change layouts for different screen widths, orientations, or display resolutions. The footgun is only testing for width, ignoring other factors.

WHY IT EXISTS Websites are viewed on a vast range of devices, from tiny phone screens to massive wall-mounted displays. A single, rigid design cannot serve all these contexts well. Media queries were created to allow a document's presentation to be tailored to the specific capabilities of the device it's being viewed on.

THE MENTAL MODEL Think of media queries as 'if' statements for your CSS. You ask the browser questions about its environment: 'Is the screen wider than 800 pixels?', 'Is the device held in landscape mode?', 'Can this display render high-resolution images?'. If the conditions are met, a specific set of styles is applied.

HOW IT WORKS In a CSS file, you use the @media rule followed by a condition. The condition can be a media type (like screen or print) or a media feature (like (min-width: 768px)). Any CSS rules inside the curly braces of the @media block will only be applied if the browser's current state matches the query. You can combine multiple conditions with keywords like and, or, and not to create more complex logic.

WHEN TO USE IT Media queries are the foundation of responsive web design. Use them to change layouts based on viewport width and height. They are essential for creating different experiences for screen versus print. You can also use them to adapt to device orientation (portrait vs. landscape) or even for foldable devices by querying horizontal-viewport-segments.

WHEN NOT TO USE IT Avoid using media queries to guess a specific device. For example, do not write a query assuming (max-width: 480px) is always a phone. A user could have a small browser window on a large desktop monitor. Always style for the properties of the viewport, not the assumed device in that viewport.

ONE CANONICAL EXAMPLE A common pattern is a multi-column layout on a wide screen that collapses to a single, scrollable column on a narrow screen. You would write: @media (max-width: 600px) { .container { flex-direction: column; } }. This tells the browser to apply the column layout only when the viewport width is 600 pixels or less.

Read the original → w3.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.