惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
V2EX
博客园 - 三生石上(FineUI控件)
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
D
Docker
S
SegmentFault 最新的问题
博客园 - 聂微东
美团技术团队
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
F
Fortinet All Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
GbyAI
GbyAI
L
LangChain Blog
Vercel News
Vercel News
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
Engineering at Meta
Engineering at Meta
T
Threat Research - Cisco Blogs
T
Threatpost
Scott Helme
Scott Helme
T
Tailwind CSS Blog
Latest news
Latest news
Stack Overflow Blog
Stack Overflow Blog
Blog — PlanetScale
Blog — PlanetScale
The Register - Security
The Register - Security
罗磊的独立博客
P
Proofpoint News Feed
腾讯CDC
S
Schneier on Security
雷峰网
雷峰网
A
About on SuperTechFans
T
Tenable Blog
F
Full Disclosure
Cyberwarzone
Cyberwarzone
博客园_首页
有赞技术团队
有赞技术团队
K
Kaspersky official blog

DEV Community

Bringing MongoDB Atlas and Voyage AI to Dify: Build RAG Workflows and Data Agents Without Heavy Glue Code Intel Targets World's First Mass Production of Glass Substrates for AI Chip Packaging Stop Burning Tokens on Chat / Agent Loops — Here's What Actually Works 🔮 Hermes Agent 🤖: A Practical Guide 🔥 — and How It Stacks Up Against OpenClaw & GoClaw 📊 CSS @function Agent Payment Stablecoin Fallbacks: Do Not Retry the Changed Quote Daily-summary-agent Opus 4.8 barely moved the leaderboard. It moved the one number that decides if your agents can be trusted. I Built an AI Interview Coach That Turns Any Resume Into a Personalized Prep Package — No API Keys Needed The best Claude Code agents are defined by what they refuse to do I Built a Tiny Skeleton Loader for React Why I Generated Synthetic Patients to Make Identity Matching Better SPIFFE Compliance Deep Dive PostgreSQL 08007 오류 원인과 해결 방법 완벽 가이드 I Was Tired of Writing Daily Standups, So I Built an AI Agent using claude code I got tired of LLM observability tools getting acquired. So I built one that can't be. Oracle ORA-00072 오류 원인과 해결 방법 완벽 가이드 Multi-Agent Negotiation Protocols: How AI Agents Should Bargain for Resources uBlock Origin No Longer Works on Chrome - Here Are the Best Alternatives in 2026 SSH Agent Forwarding vs ProxyJump: Why Agent Forwarding Is Dangerous and What to Use Instead The Best Technology Disappears I Built a Production-Oriented Multi-Provider AI Chatbot in Rust — Here's How Markov Chain Coin Sequence: E[HH] vs E[HTH] Explained LLM Deal Flow Automation in CRM The Do-Over Game: Nash Equilibrium at the Golden Ratio Cash Flow Waterfall Model for LBO Automated Client Reporting The Monty Hall Problem: Why Switching Wins 2/3 of the Time Chat With Your Database Using Natural Language: The Future of Business Analytics Google Apps Script Automation Amoeba Extinction Probability: The Branching Process Solution RAG Architecture Deep Dive Real-Time KPI Dashboards OpenAI Agents SDK的5个隐藏用法 🔥 Algorithmic Trading Pipelines 131 tokens per second on GPU under Kubernetes one of the best blogs about hermes agent Nous Research Hermes Agent: Setup and Tutorial Guide Day 20 - AWS Lambda Spending Hours Designing the UI? Or Just Telling AI the Pain Story Karpenter on AKS in 2026: What Actually Works I built a Chrome extension that shows your ChatGPT token usage in real-time Day 1 Field Report — Barriers to an Autonomous Agent Earning Money Online Mastering Background Processing in Rails 8: Sidekiq & Redis Optimization I shipped three fixes to my product in seven days. All three came from readers. Claude Code Model Switching: The Verification Notes That Could Save You $200/Month Three agent-memory threads this week, one missing field The Way to Break Through: Why Others Sail Through While You Struggle Simple Snap Layout Overlay for Tauri v2 CSS Animation vs Lottie: Which Should You Use in 2025? How to Add Lottie Animations to Vue.js (2025 Guide) Building BayouOps Suite Pro — Lightweight Operational Readiness & Visibility for IT Teams Detecting Adversary-in-the-Middle (T1557) with Data Science HTTP Headers Every Developer Should Know (2026) Detecting Ingress Tool Transfer (T1105) with Python Linux Command Line: The 25 Commands I Use Every Day (2026) Starting My Cybersecurity Learning Journey 🚀 CSS in 2026: Modern Techniques You Might Not Know (2026) TypeScript Deep Dive: Advanced Types and Patterns (2026) Three SQL Injection Patterns That Still Ship in Node.js — And the ESLint Rule That Catches Them From Idea to Production: How I Built a Decoupled Chatbot Ordering Engine I Spent 8 Months Building a Framer Killer as a Solo Undergrad. Here's What Happened. unknown 5 Git Commands I Wish I Knew 5 Years Ago How to Find users who don't follow you back in Github Bulk-check DNS, SSL and email auth for a whole list of domains (no scraping) Monolithic vs Microservices Architecture: Which One Should You Choose? The Full-Stack Developer's 2026 Playbook: 7 Shifts That Separate Senior Engineers from the Rest MCP Tool Budget for AI SaaS: Stop Agents From Burning Tokens, Tools, and Trust Untrusted Code, Trusted Cluster Scaling Secure AI Agent Workspaces with GKE Agent Sandbox Learning, Experimenting - Concurrency in Go Building Dhrishti Part 2: Go-Lang Quirks Announcing My New Book: Web Automation with Playwright and Python using AI and MCP Why MTP Batch Transfers Slow Down Between Files How We Cut Our AI Coding Bill by 65% Without Sacrificing Quality Claude vs Gemini Across 4 Security Domains: A Dead Heat — and the Hardening 63% of AI Code Skips I Benchmarked 4 Lightweight Transformers for Fault Detection. Here's What Survived. 🗡️ Tsundoku Slayer: An Agent That Decides What Not To Read Animated Icons for Web Apps — The Complete 2025 Guide How to Use Lottie Animations in React (2025 Guide) Azure API Management - Deploy gRPC API on Azure API management using self hosted gateway I Built pretext-pdf: Serverless PDFs Without Chromium Lottie JSON vs .lottie Format — What's the Difference and Which Should You Use? SVG Icon Systems in 2025 — Everything You Need to Know My Trading Bot Tried to Execute the Same Trade Twice. That Became SafeAgent. Free Loading Animations for Web Apps — Lottie, GIF, and SVG Spinners (2025) How to Add Lottie Animations to Your Website (Free JSON Files Included) Idempotency Keys: The One API Pattern That Prevents Duplicate Payments (and Worse) CONFIGURING SEMANTIC MODEL IN POWER BI Surviving Global Vendor Outages: Federated Cellular Architecture with EKS, AKS, and Istio I Turned My Cursor + Claude Code Setup Into 12 Reusable Files I Built a Cognitive Threat Hunter on Hermes Agent — It Analyzed the Session Where I Built It and Found Three Blind Spots Making AI-Generated Code Fail Gracefully How to Convert Lottie JSON to GIF (Free, Browser-Based, No Signup) Observability 2.0: Tracing AI "Thought Chains" with OpenTelemetry Best Free Lottie Animation Tools in 2025 (No Signup, No Paywall) What Is a Function in Scala Three ways to gate an MCP server: OAuth, L402, and proof-of-work You don't know kubectl — you know how to Google kubectl. The first-principles fix. Building a DevOps Incident Investigator with Coral SQL — From 15 Minutes to 15 Seconds
CSS @function
Koushik Radhakrishnan · 2026-05-31 · via DEV Community

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),
    transparent calc(var(--alpha) * 100%)
  );
}

.overlay {
  background: --fade(royalblue, 0.3); /* 70% opaque blue */
}

Enter fullscreen mode Exit fullscreen mode

Logic Inside Functions

This is where @function gets genuinely exciting. You can embed @media or @supports queries right inside a function to return different values based on conditions.

@function --responsive-font(--sm, --lg) {
  result: var(--sm); /* mobile default */

  @media (min-width: 768px) {
    result: var(--lg); /* larger screen override */
  }
}

h1 { font-size: --responsive-font(24px, 48px); }
p  { font-size: --responsive-font(15px, 18px); }

Enter fullscreen mode Exit fullscreen mode


3. Real-World Examples

Example 1 — Theme-Aware Sizing (Light/Dark)

The built-in light-dark() function only works with color values. With @function, you can extend that same idea to any CSS property — font weights, border radius, letter spacing, anything.

@function --theme-val(--light, --dark) {
  result: var(--light);

  @media (prefers-color-scheme: dark) {
    result: var(--dark);
  }
}

button {
  font-weight: --theme-val(500, 400);
  border-radius: --theme-val(6px, 2px);
  letter-spacing: --theme-val(0em, 0.03em);
}

Enter fullscreen mode Exit fullscreen mode

Example 2 — Color Opacity Shorthand

Stop writing color-mix() from scratch every time you need a translucent variant of a color.

@function --alpha(
  --c <color>,
  --a <number>: 0.5
) returns <color> {
  result: color-mix(
    in srgb,
    var(--c) calc(var(--a) * 100%),
    transparent
  );
}

.modal-bg { background: --alpha(#0f0f0f, 0.7); }
.chip      { background: --alpha(royalblue, 0.15); }
.highlight { background: --alpha(gold, 0.3);      }

Enter fullscreen mode Exit fullscreen mode


4. Why This Beats Sass/SCSS for These Use Cases?

Let's be clear — Sass isn't going away. But @function directly replaces its most common use case: reusable value computation. Here's why the native approach wins:

  • No build step. Your function evaluates at runtime in the browser, not at compile time. It can react to live conditions like viewport size or user preferences.
  • Works with custom properties. You can pass var(--token) directly as a function argument. Sass couldn't dynamically read runtime custom property values.
  • Type safety. Declare parameter types and return types. The browser validates them — something Sass never did natively.
  • Ships in your CSS. Devtools can inspect it, browser can cache it. Zero toolchain friction.

5. Browser Support & Current Limitations

🔴 @function shipped in Chrome 139 (May 2025) and is supported across Chrome, Edge, and Opera (~67% of global users). Firefox and Safari are still pending — production use without a fallback affects ~33% of users.

🚫 No recursion. A function cannot call itself. Recursive patterns need to stay in JavaScript.

🚫 No side effects. Functions can only compute and return a value. You can't modify a DOM element's class or trigger an animation directly from inside a function.

⚠️ Name must start with --. Easy to forget. --my-fn() works; myFn() does not.

⚠️ Spec is still evolving. Some details (like interaction with cascade layers) are still being refined in the css-mixins-1 spec. Treat this as stable-but-maturing.

⚠️ No cross-file imports natively. Functions defined in one CSS file are not automatically available in another unless you use @import or bundle them together.

💡 Progressive Enhancement Strategy
Use @supports to check for @function support, or define a plain var() fallback first and layer your function-based values on top. Users on unsupported browsers will get the fallback; Chrome/Edge users get the enhanced version.


If this was useful, share it with your frontend team. Drop a comment with the most creative use case you can think of — I'd love to see what people build with this. 👇