tezvyn:

The @media Rule: CSS for Different Screens

AI-drafted, machine-checkedSource: Wikipedia: CSS media queriesbeginner

The @media rule is like an if-statement for your CSS, applying styles only when conditions like screen size are met. It's the core of responsive design, creating different layouts for mobile, tablet, and desktop.

WHY IT EXISTS: In the early web, sites were designed for one screen size: a desktop monitor. The rise of mobile phones, tablets, and huge displays broke this assumption. We needed a way to make one website look good everywhere without building and maintaining separate sites for each device.

THE MENTAL MODEL: Think of @media as conditional logic for your styles. It asks questions about the device viewing your page—for example, "Is this screen smaller than 600 pixels wide?" or "Is this page being printed?"—and applies a block of CSS rules only if the answer is yes.

HOW IT WORKS: You wrap CSS rules inside an @media block. The block starts with @media followed by a condition, called a media feature, in parentheses. For example, @media (max-width: 600px) { ... } applies the enclosed styles only if the viewport is 600 pixels wide or less. You can combine conditions using keywords like and, or, and not to create more specific rules.

WHEN TO USE IT: Use @media queries to build responsive layouts, which is standard practice for modern web development. Common use cases include: changing grid layouts from a single column to multiple columns, hiding non-essential elements on small screens, and adjusting font sizes for readability on different devices.

WHEN NOT TO USE IT: Don't use @media queries for everything. For simple adjustments that depend on a component's container size rather than the whole screen, newer container queries (@container) are often a better fit. Overusing complex or deeply nested media queries can also make your CSS difficult to read and maintain.

ONE CANONICAL EXAMPLE: A common pattern is a "mobile-first" approach. You write the base styles for a small screen by default. Then, you use @media with a min-width condition to add or override styles for larger screens. For instance, a single-column layout for a container might become a two-column grid on screens wider than 768 pixels by changing its display property inside an @media (min-width: 768px) block.

Read the original → en.wikipedia.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.