CSS conditional rules represent one of the most powerful evolutions in styling web interfaces. These rules enable developers to apply styles conditionally, based on the capabilities of the user's browser, the dimensions of the viewport or container, or the computed values of elements themselves. Rather than writing universal styles and hoping they work everywhere, conditional rules let us craft targeted, context-aware styling strategies that adapt to each user's unique situation.
The CSS Conditional Rules module has expanded significantly since its introduction. Originally focused on media types like screen and print, it now encompasses feature queries, container queries, and soon generalized conditional rules with @when and @else. This evolution reflects the increasing complexity of web interfaces and the need for more granular control over how styles are applied.
Modern web development requires understanding these conditional systems to create truly adaptive interfaces that perform well across all devices and browser capabilities.
The @media Rule: Viewport-Based Conditions
The @media rule has been the cornerstone of responsive web design since its introduction. It allows styles to be applied based on characteristics of the viewport and device, such as width, height, orientation, resolution, and user preferences. Media queries use a familiar syntax that combines media types with media features through logical operators.
1/* Basic breakpoint example */2@media (min-width: 768px) {3 .sidebar {4 display: block;5 width: 250px;6 }7}8 9/* Complex media query with multiple conditions */10@media (min-width: 1024px) and (prefers-reduced-motion: no-preference) {11 .animation {12 animation: slideIn 0.5s ease-out;13 }14}15 16/* Orientation and resolution combined */17@media (orientation: portrait) and (min-resolution: 2dppx) {18 .hero-image {19 background-image: url('hero-2x.jpg');20 }21}Media features cover a wide range of conditions. Viewport-based features like width, height, min-width, and max-width remain the most commonly used. Device features include resolution, device-pixel-ratio, and orientation. User preference features like prefers-color-scheme, prefers-reduced-motion, and prefers-reduced-data enable styles that respect user settings and accessibility needs.
When building responsive interfaces, combining @media with our CSS Transforms techniques creates smooth visual experiences across all screen sizes.
The @supports Rule: Feature Detection
The @supports rule implements feature detection directly in CSS, allowing styles to be applied only when the browser understands and can render specific properties or values. This approach enables progressive enhancement, where modern browsers receive enhanced experiences while older browsers fall back to simpler but functional designs.
1/* Progressive enhancement with CSS grid */2@supports (display: grid) {3 .layout {4 display: grid;5 grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));6 gap: 1.5rem;7 }8}9 10/* Fallback for browsers without subgrid */11.subgrid-element {12 display: grid;13 grid-template-columns: subgrid;14}15 16@supports not (grid-template-columns: subgrid) {17 .subgrid-element {18 display: flex;19 gap: 1rem;20 }21}Modern CSS features often require feature detection before use. Properties like backdrop-filter, clamp(), aspect-ratio, and container query units may not be supported in older browsers. The @supports rule also detects function support, such as calc(), min(), max(), and clamp(), enabling fallback strategies for mathematical expressions.
Container Queries: Element-Based Responsive Design
Container queries represent the most significant advancement in responsive styling methodology. Unlike media queries that respond to viewport dimensions, container queries enable styles to adapt based on the dimensions of a containing element. This shift is fundamental for component-based development, where components need to respond to their local container rather than the global viewport.
1/* Creating a query container */2.card-container {3 container-type: inline-size;4 container-name: card;5}6 7/* Querying the container by name */8@container card (min-width: 400px) {9 .card {10 display: grid;11 grid-template-columns: 150px 1fr;12 gap: 1.5rem;13 }14}The container-type property establishes an element as a query container. Values include size for queries on both axes, inline-size for queries on the inline axis only, and scroll-state for scroll position queries. When a container type is specified, the browser applies containment, isolating the container's layout from its descendants to prevent circular dependencies.
Container queries work seamlessly with our CSS Nesting patterns for cleaner, more maintainable component styles.
Container Style Queries: Querying Computed Styles
Container style queries extend the concept of container queries beyond dimensions. They allow styles to be applied based on the computed values of container properties, including custom CSS properties. This capability enables sophisticated theming systems and state-based styling that responds to calculated values rather than just physical dimensions.
1/* Setting custom properties on a container */2.card {3 container-type: inline-size;4 --theme: light;5 --emphasis: normal;6}7 8/* Querying container styles */9@container style(--emphasis: high) {10 .card-title {11 font-weight: 700;12 color: var(--primary-color);13 }14}15 16@container style(--theme: dark) {17 .card {18 background: #1a1a2e;19 color: #eee;20 }21}Style queries work with any CSS property that can be computed, including custom properties. This makes them particularly powerful for implementing design systems where components respond to theme tokens or state indicators. The syntax uses the style() function within the container query condition.
Container Relative Units
Container relative units provide a way to size elements relative to their query container's dimensions, similar to how viewport units relate to the viewport. These units enable truly component-relative styling that adapts within container contexts.
| Unit | Reference |
|---|---|
| `cqw` | 1% of container's width |
| `cqh` | 1% of container's height |
| `cqi` | 1% of container's inline size |
| `cqb` | 1% of container's block size |
| `cqmin` | Smaller of cqw and cqh |
| `cqmax` | Larger of cqw and cqh |
1/* Fluid typography using container units */2.responsive-text {3 font-size: clamp(1rem, 4cqi, 2rem);4}5 6/* Container-relative spacing */7.card {8 padding: 2cqi 1.5cqb;9}Container units are particularly valuable for fluid typography and spacing that should scale proportionally within a component. They enable designs that maintain visual harmony regardless of the container's size, eliminating the need for multiple breakpoints within individual components.
The @when and @else Rules
The CSS Conditional Rules Module Level 5 introduces @when and @else as generalized conditional rules that combine multiple query types in flexible boolean expressions. These rules simplify complex conditional logic that previously required nested queries.
1/* Combined media and supports query */2@when media(width >= 600px) and supports(display: grid) {3 .grid-layout {4 display: grid;5 }6}7 8/* Conditional chain with @else */9@when font-tech(color-COLRv1) and font-tech(variations) {10 @font-face { font-family: icons; src: url('icons-gradient-var.woff2'); }11}12@else font-tech(color-SVG) {13 @font-face { font-family: icons; src: url('icons-gradient.woff2'); }14}Performance and Best Practices
Performance optimization for conditional rules involves understanding how browsers evaluate and cache query results. Container queries require containment on the container element, which the browser uses to isolate query evaluation from descendant changes.
1/* Efficient container usage */2.card-wrapper {3 container-type: inline-size;4 contain: layout inline-size;5}6 7/* Performance-conscious query ordering */8@container (max-width: 400px) {9 /* Mobile-first within container */10}11 12@container (min-width: 401px) and (max-width: 800px) {13 /* Tablet range */14}Group Related Queries
Keep related conditional rules together for maintainability and easier debugging.
Use Named Containers
Assign meaningful names to containers for precise targeting in complex layouts.
Prefer rem Units
Use rem units for breakpoints to respect user font size preferences and accessibility.
Provide Fallbacks
Always include fallback styles for browsers that don't support newer features.
For more on performance optimization, see our guide to CSS Easing Functions for smooth animations in responsive designs.
Frequently Asked Questions
Conclusion
CSS conditional rules have evolved from simple media type detection to a sophisticated system for context-aware styling. The combination of @media, @supports, @container, and the emerging @when/@else rules provides developers with powerful tools to create truly adaptive interfaces. Container queries, in particular, represent a paradigm shift toward component-based responsive design, enabling components to respond to their local context rather than the global viewport.
Mastering these conditional rules requires understanding not only their syntax but also their performance implications, accessibility considerations, and browser support status. By applying these techniques thoughtfully, developers can build interfaces that adapt gracefully to diverse devices, user preferences, and contexts while maintaining clean, maintainable stylesheets.
Our CSS Value Functions guide covers complementary techniques for creating fluid, adaptive layouts that work seamlessly with conditional rules.
Sources
-
MDN Web Docs - CSS conditional rules - Comprehensive official documentation
-
MDN Web Docs - Container size and style queries - Technical implementation details
-
Josh W. Comeau - A Friendly Introduction to Container Queries - Tutorial with practical examples
-
CSS-Tricks - Digging Deeper Into Container Style Queries - Advanced use cases
-
W3C CSS Conditional Rules Module Level 5 - Official specification