Mastering CSS Inline Conditional Functions (if()) in Chrome 137
Starting with Chrome 137, CSS introduces the inline conditional function if(), allowing developers to embed conditional logic directly in style rules, reducing reliance on @media and @supports and making styles more concise, direct, and flexible.
What is if() ?
if()is a CSS function that selects different style values based on conditions, similar to JavaScript's if...else.
It supports three condition types: media(): media queries for screen size, orientation, etc. supports(): feature queries to check browser support for a CSS feature. style(): style value queries, often used with CSS variables to evaluate element state.
Basic syntax:
property: if(
condition-1: value-1;
condition-2: value-2;
/* … */
else: value-n);The else clause is optional and provides a default value.
Using if() offers three advantages:
More concise : logic and styles are written together, reducing fragmented code.
More direct : style() can reference an element's own properties without relying on parent elements.
More flexible : works with variables, functions, and other modern CSS features for dynamic styling.
Application Scenarios
Inline Media Queries
Switch card layout based on screen orientation:
.card-container {
flex-direction: if(
media(orientation: landscape): row;
else: column);
}Uses a horizontal layout in landscape mode and a vertical layout in portrait mode.
Inline Supports Queries
Add a backdrop‑filter effect when the browser supports it:
.modal {
background: if(
supports(backdrop-filter: blur(10px)):
rgba(255, 255, 255, 0.6);
else:
#ffffff);
backdrop-filter: if(
supports(backdrop-filter: blur(10px)):
blur(10px));
}Uses a semi‑transparent background with blur when supported, otherwise falls back to solid white.
State‑Based Styles
Change text color based on theme mode:
<div class="text" data-theme="dark">Welcome to inline if()</div> .text {
--theme: attr(data-theme);
color: if(
style(--theme: dark): #f1f1f1;
style(--theme: light): #222;
else: #444);
}Applies light text on dark themes and dark text on light themes.
Browser Support
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
