Back to Home
CSS @function

CSS @function

B
Blizine Admin
·2 min read·0 views

Koushik Radhakrishnan Posted on May 31 CSS @function # css # webdev # frontend # styling CSS just got its biggest quality-of-life upgrade since custom properties. For years, if you wanted reusable logic in CSS, you had two choices: wrestle with custom properties that couldn't do real computation, or reach for a preprocessor like Sass. That era just quietly ended. CSS now has native custom functions — and they're as powerful as you'd hope. 1. What Exactly Is @function ? Think of it exactly like a JavaScript function — but living inside your stylesheet. You give it a name (always prefixed with -- ), define some parameters, and write a result: descriptor that determines what it returns. /* BASIC SYNTAX */ /* Define it once */ @function --double ( --x ) { result : calc ( var ( --x ) * 2 ); } /* Call it anywhere */ .box { width : --double ( 20px ); /* → 40px */ height : --double ( 50px ); /* → 100px */ } Enter fullscreen mode Exit fullscreen mode No var() wrapper needed to call it. No build step. No Sass import. Just define and use — as many times as you like, across your entire stylesheet. Note: Unlike Sass, native CSS functions don't evaluate math automatically. You must wrap mathematical operations in calc() inside your result descriptor. 2. The Syntax in Full Detail Parameters with Default Values You can make parameters optional by giving them a fallback — the function still works even if you don't pass a value. @function --spacing ( --size : 16px ) { result : calc ( var ( --size ) * 1.5 ); } .card { padding : --spacing (); /* → 24px (uses default) */ margin : --spacing ( 20px ); /* → 30px */ } Enter fullscreen mode Exit fullscreen mode Type-Safe Parameters You can declare the expected type of each parameter — and the return type too. The browser will validate this at parse time, preventing weird cascading bugs. @function --fade ( --color < color > , --alpha < number > : 0.5 ) returns < color > { result : color-mix ( in srgb , var ( --color ), trans

📰Dev.to — dev.to

Comments