Using the upcoming CSS when/else rules
CSS is always evolving, and new proposed rules provide extra features that you should be aware of. This article will explain two new expansions, @when and @else, so that you can be prepared.
Discover how at OpenReplay.com.
Using CSS when/else rules
If you have wondered why CSS holds such importance in web development, the answer becomes clear once you understand its role in shaping the visual aspects of websites. As we all know, CSS (Cascading Style Sheets) plays a significant role in developing good-looking web pages as they control the layout, colors, fonts, and various design elements. However, what if there was a way to go beyond the traditional approach and apply styles conditionally based on specific criteria? In this article, we will explore the proposed CSS @when/@else
rules, which can enable developers to achieve precisely that.
It’s important to note that these rules are still in the proposal stage and are not part of the standard CSS implemented in browsers yet. Therefore, they cannot be used in production environments at this time. Developers can look forward to these features being adopted in the future, which will enhance the power and flexibility of CSS for conditional styling. Please see this W3C module for more information.
That being said, let’s dive in to understand what the @when/@else
rules are.
Understanding CSS @when/@else
rules
With CSS, @when/@else
rules provide a mechanism for applying styles selectively based on specific conditions. In simpler terms, they allow developers to define a set of styles to be applied when a condition is met and an alternative set of styles when it is not. This approach differs from traditional CSS, where styles are applied universally.
Below is a table that distinguishes the @when/@else
rules from the traditional CSS.
Aspect | CSS @when/@else Rules | Traditional CSS Approaches |
---|---|---|
Selective Styling | Styles can be applied conditionally | Styles are applied universally |
Dynamic Adaptability | Allows for responsive design | Limited flexibility in styling |
Specific Conditions | Styles can be based on criteria | Styles applied without conditions |
User Interaction | Enables interactive styling | Limited interactivity |
State and Event Styling | Different styles for various states | Limited state-based styling |
Customization | Highly customizable | Less customization options |
Usability and Aesthetics | Enhances user experience | Standard styling practices |
In traditional CSS, styles are universally applied to elements that match a selector.
For example:
.nav {
display: flex;
justify-content: space-between;
background-color: #333;
color: #fff;
padding: 1rem;
}
.nav-item {
margin-right: 1rem;
}
/* Responsive styles */
@media (max-width: 768px) {
.nav {
flex-direction: column;
}
.nav-item {
margin-right: 0;
margin-bottom: 0.5rem;
}
}
This traditional CSS approach applies the main styles for the .nav
and .nav-item
universally, while the responsive styles inside the @media
target specific screen widths to modify the layout and spacing for smaller screens.
Here’s an example using the @when/@else
rule syntax:
/* Using @when and @else */
@when media(max-width: 768px) and supports(display: flex) {
.nav {
flex-direction: column;
}
.nav-item {
margin-right: 0;
margin-bottom: 0.5rem;
}
}
@else {
.nav {
display: flex;
justify-content: space-between;
background-color: #333;
color: #fff;
padding: 1rem;
}
.nav-item {
margin-right: 1rem;
}
}
As you can see, with the @when
rule, we check if the screen width is less than or equal to 768px
and if the browser supports Flexbox. If both conditions are true, the first block of styles is applied (vertical layout). Otherwise, the @else
block provides the traditional horizontal layout.
NOTE: The @when
and @else
rules simplify conditional styling, making your CSS more concise and easier to manage.
Benefits of using the @when/@else
rules
Now that we have a glimpse of CSS’s @when/@else
rules let’s explore some of its benefits.
Generalization with @when
The @when
rule generalizes conditionals, allowing you to combine different queries (such as @media
and @support
) into a single statement. You can wrap multiple conditions into one block instead of writing separate conditional rules for specific tasks.
For example, suppose you want to test whether a media screen is below 769px
and whether the browser supports both grid and flex display features. With @when
, you can create a generalized rule like this:
@when media(max-width: 769px) and supports(display: grid) and supports(display: flex) {
.grid {
grid-template-columns: 1fr;
}
.flex {
flex-direction: row;
}
}
In the above code, the @when
rule is followed by the media query condition (max-width: 769px)
and the supports
conditions for display: grid
and display: flex
. Inside the rule, the styles for the .grid
and .flex
classes are specified accordingly.
Mutually exclusive rules with @else
The @else
statement allows you to write mutually exclusive rules. If the conditions in the @when
block are evaluated as false, the CSS engine ignores that style block and falls back to default styles. For instance, you can create styles that apply only when certain conditions are met; if not, the fallback styles take effect.
Improved readability
Using comparison operators in @when
and @else
makes media queries easier to read and understand. It simplifies complex logic by combining multiple conditions into concise statements.
Support extensions
The Level 4 CSS update includes extensions to support rules, allowing testing for supported font technologies and other features.
Implementing @when/@else
rules in CSS
To implement the @when/@else
rules, we can use a combination of CSS selectors and properties.
Here’s a step-by-step guide on how to implement the @when/@else
rules in CSS:
- Check browser support: Before you start, verify if your target browser supports the
@when/@else
rules. You can check resources like “Can I use” for the most current information. - Write the base CSS: Define the base CSS styles that will apply regardless of conditions.
- Define your conditions: Determine the conditions under which you want to apply different styles. These can be based on media queries, feature support, or other environmental conditions.
- Use
@when
to apply conditional styles: Start with the@when
rule followed by your condition in parentheses. Inside the curly braces{}
, write the CSS rules that should apply when the condition is true. - Use
@else
for alternative styles: Follow the@when
block with an@else
block. Inside the@else
curly braces, write the CSS rules that should apply when the@when
condition is not met. - Test your styles: After implementing your conditional rules, test them across browsers and devices to ensure they work as expected.
Here’s an example to illustrate the process:
/* Base CSS */
.container {
padding: 20px;
}
/* Conditional CSS */
@when media(max-width: 600px) {
.container {
padding: 10px; /* Smaller padding for narrow screens */
}
}
@else {
.container {
padding: 20px; /* Default padding */
}
}
In this example, the .container
will have a padding of 10px
if the viewport width is less than 600px
. Otherwise, it will default to a padding of 20px
.
Now, let’s take a look at common use cases.👇
- Responsive design: Adjusting layout and font sizes based on viewport dimensions. For example, switching from a multi-column layout to a single-column layout on mobile devices.
- Feature detection: Applying styles only if certain CSS features are supported by the browser. For example, using grid layout styles only if the browser supports CSS Grid.
- Environment adaptation: Changing styles based on user preferences or environmental conditions like dark mode. For example, a dark color scheme can be applied if the user has set their system to dark mode.
- State-based styling: Modifying styles based on the state of an element, such as hover or focus. For example, changing the background color of a button when it is hovered over.
- Fallbacks for older browsers: Providing alternative styles for browsers that do not support modern CSS properties. For example, using flexbox as a fallback for browsers that do not support grid layout.
Here’s an example that combines responsive design and feature detection:
/* Base styles */
.container {
display: flex;
flex-wrap: wrap;
}
/* Conditional styles */
@when media(max-width: 600px) and supports(display: grid) {
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
}
@else {
.container {
display: flex;
flex-direction: column;
}
}
In this example, if the viewport is less than 600px
wide and the browser supports CSS Grid, the .container
will use a grid layout with flexible columns. If not, it will default to a flex column layout.
Advanced techniques for CSS @when/@else
rules
Advanced Techniques for CSS @when/@else
rules offer more control over styles based on different conditions like complex media queries, feature detection, or custom environmental factors. This section talks about advanced approaches and tips that help optimize the usage of @when/@else
rules.
Let’s go!
Combining with CSS preprocessors
CSS preprocessors like Sass or LESS can enhance the @when/@else
rules by allowing you to use variables, functions, and other programming concepts within your CSS.
Here’s an example using Sass:
$breakpoint: 600px;
@mixin responsive($property, $value) {
@when media(max-width: $breakpoint) {
#{$property}: $value;
}
@else {
#{$property}: adjust-value($value);
}
}
.container {
@include responsive(padding, 20px);
}
In the code above, the responsive mixin applies different padding values based on the viewport width, using a variable for the breakpoint.
To learn more about Sass, read this.
Dynamic styling based on conditions
Dynamic styling can be achieved by setting CSS variables or classes that change styles based on certain conditions. For instance, JavaScript can be used to toggle a class based on user interaction or environmental changes.
Here’s an example(JavaScript code):
window.addEventListener('resize', () => {
if (window.innerWidth < 600) {
document.body.classList.add('mobile');
} else {
document.body.classList.remove('mobile');
}
});
CSS code:
body.mobile .container {
/* Styles for mobile */
}
@else {
.container {
/* Default styles */
}
}
The JavaScript listens for window resize events and adds or removes a ‘mobile
’ class to the body, which could trigger different styles based on the @when/@else
rules.
Responsive design using @when/@else
rules
Responsive design aims to make web applications look good on all devices. With the @when/@else
rules, you could write more readable media queries.
For example:
@when media(max-width: 768px) {
.column {
width: 100%;
}
}
@else {
.column {
width: 50%;
}
}
This example changes the column width based on the viewport size, making it responsive to different device screens.
Best practices for @when/@else
rules
When working with CSS, especially with the proposed @when/@else
rules, it’s important to follow best practices to write efficient and maintainable code. Here are some tips and debugging strategies:
- Plan your CSS: Before writing your CSS, plan the styles that will be needed, the different layouts, and specific overrides. Avoid too much overriding.
- Use flexible units: For maximum flexibility, use relative units like ems, rems, percentages, or viewport units.
- Keep it consistent: Whether you’re working alone or with a team, consistency in naming conventions, color descriptions, and formatting is key.
- Comment your CSS: Comments can help you and others understand the structure and purpose of your CSS. Use them to separate logical sections.
Debugging @when/@else
rules
When you come across issues with the functionality or appearance of the @when/@else
rules, it’s important to use debugging techniques to identify and fix the underlying problems.
Here are some debugging techniques:
- Browser DevTools: Modern browsers come with DevTools that allow you to inspect elements and see which CSS rules are being applied. Use this to troubleshoot unexpected behaviors.
- Isolation: If a particular set of rules isn’t working as expected, try isolating them in a separate stylesheet or HTML document to see if other styles are interfering.
- Process of elimination: Temporarily comment out other CSS rules to see if they are causing the issue.
Conclusion
In our discussion, we explored the concept of @when/@else
rules in CSS, which are part of a proposed extension to CSS conditionals. We covered their syntax and potential use cases and provided a step-by-step guide on how they might be implemented. We also discussed advanced techniques, such as combining these rules with CSS preprocessors and using them for responsive design. Although these rules offer promising benefits for readability, maintainability, and flexibility in styling, it’s important to note that they are not yet part of the standard CSS implementation and thus are not supported in current browsers.
For further reading and learning, you can check the following resources:
- MDN Web Docs provides a comprehensive guide on CSS conditional rules, including the
@when
and@else
rules which are planned but not yet implemented. - W3cubDocs offers support tables for CSS
@when/@else
conditional rules, detailing the syntax and usage. - LogRocket Blog gives a first look at extending CSS
@when/@else
chains, including practical uses within style sheets. - Can I use provides information on the browser support and syntax for CSS
@when/@else
conditional rules.
Thank you for reading :).
Truly understand users experience
See every user interaction, feel every frustration and track all hesitations with OpenReplay — the open-source digital experience platform. It can be self-hosted in minutes, giving you complete control over your customer data. . Check our GitHub repo and join the thousands of developers in our community..