Explore the CSS @when rule, a powerful feature enabling conditional style application based on browser support, viewport size, and more. Learn with practical examples.
CSS @when Rule: Mastering Conditional Style Application
The world of CSS is constantly evolving, offering developers more powerful and flexible ways to style web pages. One such feature gaining traction is the @when
rule, also known as the CSS Conditional Rules Module Level 1. This rule allows you to apply CSS styles conditionally, based on specific conditions being met. It’s a powerful tool for responsive design, feature detection, and creating more robust and adaptable stylesheets.
What is the CSS @when Rule?
The @when
rule is a conditional at-rule in CSS that allows you to define styles that are only applied if certain conditions are true. Think of it as an if
statement for your CSS. Unlike media queries, which primarily focus on viewport characteristics (screen size, orientation, etc.), @when
provides a more general and extensible way to handle conditional styling. It expands upon existing conditional at-rules like @supports
and @media
.
Key Advantages of Using @when
- Improved Code Readability: By encapsulating conditional logic within
@when
blocks, you make your CSS easier to understand and maintain. The intent behind specific style applications becomes clearer. - Enhanced Flexibility:
@when
can handle more complex conditions than traditional media queries, particularly when combined with feature queries and JavaScript-driven logic (using CSS Custom Properties). - Simplified Feature Detection:
@when
integrates seamlessly with@supports
, allowing you to apply styles only when specific browser features are available. This is crucial for progressive enhancement. - More Semantic Styling:
@when
allows you to style elements based on their state or context, leading to more semantic and maintainable CSS. For example, styling elements based on data attributes or custom properties set by JavaScript.
Syntax of the @when Rule
The basic syntax of the@when
rule is as follows:
@when <condition> {
/* CSS rules to apply when the condition is true */
}
The <condition>
can be any valid boolean expression that evaluates to true or false. This expression often involves:
- Media Queries: Conditions based on viewport characteristics (e.g., screen width, device orientation).
- Feature Queries (@supports): Conditions based on browser support for specific CSS features.
- Boolean Algebra: Combining multiple conditions using logical operators (
and
,or
,not
).
Practical Examples of @when in Action
Let's explore some practical examples to illustrate the power and versatility of the@when
rule.
1. Responsive Design with @when and Media Queries
The most common use case for @when
is responsive design, where you adjust styles based on screen size. While media queries can achieve this on their own, @when
provides a more structured and readable approach, especially when dealing with complex conditions.
@when (min-width: 768px) and (max-width: 1023px) {
body {
font-size: 18px;
line-height: 1.6;
}
.container {
width: 720px;
margin: 0 auto;
}
}
In this example, the styles within the @when
block are applied only when the screen width is between 768px and 1023px (typical tablet size). This provides a clear and concise way to define styles for specific viewport ranges.
Internationalization Note: Responsive design is critical for a global audience. Consider varying screen sizes across different regions. For example, mobile usage is higher in some countries, making mobile-first design even more crucial.
2. Feature Detection with @when and @supports
@when
can be combined with @supports
to apply styles only when a specific CSS feature is supported by the browser. This allows you to progressively enhance your website, providing a better experience for users with modern browsers while still maintaining compatibility with older ones.
@when supports(display: grid) {
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-gap: 20px;
}
}
@when not supports(display: grid) {
.container {
/* Fallback styles for browsers that don't support grid */
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.item {
width: calc(50% - 10px); /* Adjust width for older browsers */
}
}
Here, we use @supports
to check if the browser supports CSS Grid Layout. If it does, we apply grid-based styles to the .container
. If not, we provide fallback styles using flexbox to ensure a similar layout is achieved in older browsers.
Global Accessibility Note: Feature detection is important for accessibility. Older browsers may lack support for newer ARIA attributes or semantic HTML5 elements. Provide appropriate fallbacks to ensure content remains accessible.
3. Combining Media Queries and Feature Queries
The real power of @when
comes from its ability to combine media queries and feature queries to create more complex and nuanced conditional styling rules.
@when (min-width: 768px) and supports(backdrop-filter: blur(10px)) {
.modal {
background-color: rgba(255, 255, 255, 0.8);
backdrop-filter: blur(10px);
}
}
In this example, the .modal
element will only have a blurred backdrop when the screen width is at least 768px and the browser supports the backdrop-filter
property. This allows you to create visually appealing effects on modern browsers while avoiding potential performance issues or rendering glitches on older ones.
4. Styling Based on Custom Properties (CSS Variables)
@when
can also be used in conjunction with CSS Custom Properties (also known as CSS variables) to create dynamic and state-driven styling. You can use JavaScript to update the value of a custom property, and then use @when
to apply different styles based on that value.
First, define a custom property:
:root {
--theme-color: #007bff; /* Default theme color */
--is-dark-mode: false;
}
Then, use @when
to apply styles based on the value of the custom property:
@when var(--is-dark-mode) = true {
body {
background-color: #333;
color: #fff;
}
a {
color: #ccc;
}
}
Finally, use JavaScript to toggle the value of the --is-dark-mode
custom property:
document.getElementById('darkModeToggle').addEventListener('click', function() {
document.documentElement.style.setProperty('--is-dark-mode', this.checked);
});
This allows users to switch between light and dark themes, with the CSS dynamically updating based on the custom property value. Note that direct comparison of CSS variables in `@when` might not be universally supported across browsers. Instead, you might need to use a workaround with a media query checking for a non-zero value:
@when ( --is-dark-mode > 0 ) { ... }
However, ensure the custom property has a numeric value for this to function correctly.
Accessibility Note: Providing alternative themes (e.g., dark mode) is crucial for accessibility. Users with visual impairments may benefit from high-contrast themes. Ensure that your theme switch is accessible via keyboard and screen readers.
5. Styling Based on Data Attributes
You can also use @when
with data attributes to style elements based on their data values. This can be useful for creating dynamic interfaces where elements change appearance based on user interaction or data updates.
For example, let's say you have a list of tasks, and each task has a data-status
attribute that indicates its status (e.g., "todo", "in-progress", "completed"). You can use @when
to style each task differently based on its status.
[data-status="todo"] {
/* Default styles for todo tasks */
color: #333;
}
@when attribute(data-status string equals "in-progress") {
[data-status="in-progress"] {
color: orange;
font-style: italic;
}
}
@when attribute(data-status string equals "completed") {
[data-status="completed"] {
color: green;
text-decoration: line-through;
}
}
Note: support for the attribute() test condition might be limited or not fully implemented across all browsers currently. Always test thoroughly.
Browser Compatibility and Polyfills
As of late 2024, browser support for the @when
rule is still evolving. While many modern browsers support the core functionality, some older browsers may not. Therefore, it's crucial to check compatibility tables and use appropriate fallbacks or polyfills where necessary.
Always consult resources like Can I use... to check the current browser support status of @when
and related features.
Best Practices for Using @when
- Keep Conditions Simple: Avoid overly complex conditions within
@when
blocks. Break down complex logic into smaller, more manageable chunks. - Provide Fallbacks: Always provide fallback styles for browsers that don't support the features you're using in your
@when
rules. This ensures a consistent experience across different browsers. - Test Thoroughly: Test your CSS in a variety of browsers and devices to ensure that your
@when
rules are working as expected. - Use Meaningful Comments: Add comments to your CSS to explain the purpose of each
@when
rule and the conditions it's based on. This will make your code easier to understand and maintain. - Consider Performance: Avoid using
@when
rules excessively, as they can potentially impact performance. Optimize your CSS to minimize the number of rules that need to be evaluated.
Conclusion
The @when
rule is a powerful addition to the CSS toolbox, offering developers a more flexible and expressive way to apply styles conditionally. By combining it with media queries, feature queries, and CSS Custom Properties, you can create more robust, adaptable, and maintainable stylesheets. While browser support is still evolving, @when
is a feature worth exploring and incorporating into your modern web development workflow.
As the web continues to evolve, mastering features like @when
will be essential for creating engaging, accessible, and performant experiences for users around the world. Embrace the power of conditional styling and unlock new possibilities in your CSS development.