The CSS `if()` function has officially been released in Chrome 137. This feature was resolved to be added by the CSSWG less than a year ago, marking a swift development process. Typically, such features take years to develop, but here we are with the `if()` function available for use.
The goal is not to debate the existence of `if()` in CSS or whether CSS is a programming language, as those discussions have been addressed by others. Instead, the focus is on exploring the `if()` function in its early days of support and understanding its syntax. A deeper dive with real-world examples will follow in an upcoming post.
Conditional statements have always been a part of CSS, from at-rules to DOM parsing. As Lea Verou noted, every selector is essentially a conditional. However, CSS lacked the capability to style an element based on multiple conditions in a single line. The `if()` function now allows for advanced conditionals, enabling multiple conditional statements to be assigned to a single property.
“`css
.element {
color: if(style(–theme: dark): oklch(52% 0.18 140); else: oklch(65% 0.05 220));
}
“`
The syntax for `if()` has evolved since its initial proposal in 2021. The current syntax is:
“`css
[
)
“`
The first `
Here’s an example of changing an element’s padding based on a color scheme:
“`css
.element {
padding: if(style(–theme: dark): 2rem; else: 3rem);
}
“`
Complexity can arise with multiple `if()` statements, but formatting can enhance readability:
“`css
:root {
–height: 12.5rem;
–width: 4rem;
–weight: 2rem;
}
.element {
height: if(
style(–height: 3rem): 14.5rem;
style(–width: 7rem): 10rem;
style(–weight: 100rem): 2rem;
else: var(–height)
);
}
“`
The `supports()` function works like the `@supports` at-rule but returns a value instead. For instance:
“`css
.card {
backdrop-filter: if(
supports(backdrop-filter: blur(10px)): blur(10px);
else: unset
);
}
“`
Similarly, the `media()` function parallels the `@media` at-rule:
“`css
h1 {
font-size: if(
media(width >= 1200px): 3rem;
media(width >= 768px): 2.5rem;
else: 2rem
);
}
“`
Currently, only the latest Chrome update supports `if()`. Other browsers may follow as usage grows. Experimenting with new features helps CSS evolve, and feedback to CSSWG and Chromium can aid future implementations. A more in-depth article on `if()` with real-world applications is forthcoming.
Discover more from WIREDGORILLA
Subscribe to get the latest posts sent to your email.