CSS @function: Dynamic logic without Sass or JavaScript - LogRocket Blog
Briefly

CSS @function: Dynamic logic without Sass or JavaScript - LogRocket Blog
"But the platform is catching up. After the arrival of custom properties and native nesting, CSS is making another leap forward with @function. Where variables let us store static values, custom functions let us compute dynamic ones - finally bringing reusable logic directly into CSS. In this guide, we'll explore practical patterns where @function replaces old Sass or JavaScript utilities, helping you write leaner, more expressive stylesheets."
"The key mental shift is moving from static values to dynamic logic. We've had CSS Custom Properties (variables) for years, and they are excellent for storing and reusing static values like a brand color or a spacing unit. :root { --brand-color: #3498db; } A @function, however, doesn't just store a value; it computes one. It takes inputs and returns an output, allowing you to encapsulate logic directly in your CSS. @function --adjust-lightness(--color, --amount) { ... }"
"Introducing logic with native if() The real power of custom functions is unlocked when you combine them with conditional logic. The new native CSS if() function lets you create simple if/else statements directly inside a function's declaration. Let's build a simple, colorful component to demonstrate this. We'll create a "status card" that changes its theme (color and icon) based on a custom property switch."
CSS custom functions (@function) bring programmable logic into stylesheets by accepting inputs and returning computed outputs. Custom properties remain useful for static values while @function supports dynamic calculations and encapsulated logic such as color adjustments. Native if() enables conditional behavior inside functions, permitting theme switches and state-dependent styling without external scripts. Patterns that previously required Sass functions or JavaScript—like pixel-to-rem conversions or theme toggles—can now be implemented natively. Examples include an @function --adjust-lightness(--color, --amount) and a status card that changes color and icon based on a custom property. Native functions help produce leaner, more expressive CSS.
Read at LogRocket Blog
Unable to calculate read time
[
|
]