搜尋
首頁web前端css教學CSS 變數的驚人細節 - 使用 var() 和很酷的範例

This is the second half of my CSS Variable post, the first half is here.
In this article we'll look into the details of var(). And two cool examples:

  • Animation using CSS Variables
  • Pure CSS dark mode toggle with system setting detection

The Surprising Details of CSS Variables - Using var() and Cool Examples

Using var()

The var() accesses custom property values (CSS variables). Its syntax is as follows:

var( <custom-property-name>, <fallback-value>? )
</fallback-value></custom-property-name>

Basic Rules

  1. The first parameter must be a CSS variable: Direct values, such as var(20px), will result in an error, as var() only accepts custom property names.

  2. var() cannot replace property names: In other words, you cannot write something like var(--prop-name): 20px; because var() is limited to use in property values only.

.foo {
  margin: var(20px); /* Error, 20px is not a CSS variable */

  --prop-name: margin-top;
  var(--prop-name): 20px; /* Error, cannot use var() this way */
}

Detailed Behaviors

  1. var(--b, fallback_value) Fallbacks: The second parameter acts as a fallback value, used when --b is invalid.

  2. var(--c,) Syntax with an Empty Fallback: If the fallback value is left empty, the syntax remains valid and will default to an empty value if --c is invalid.

  3. Multiple Comma: In var(--d, var(--e), var(--f), var(--g)), everything after the first comma is treated as fallback, so if --d is invalid, the var() expression evaluates var(--e), var(--f), var(--g) as one fallback, to determine the result.

  4. var() as a Complete CSS Token: The function acts as a complete CSS token, like 20px would. Therefore, var(--size)var(--unit) will not create 20px and is considered invalid.

  5. Using initial with CSS Variables: Assigning initial to a CSS variable means it is invalid. To display initial as a value, it must be placed in the fallback.

  6. url() and var() Usage: Since url() is treated as a complete CSS token, you need to define the full url() within the variable.

:root {
  /* 1. */
  margin: var(--b, 20px); /* Uses 20px if --b is invalid */

  /* 2. */
  padding: var(--c,) 20px; /* Falls back to 20px if --c is invalid */

  /* 3. */
  font-family: var(--fonts, "lucida grande", tahoma, Arial); /* Uses fallback font stack if --fonts is invalid */

  /* 4. */
  --text-size: 12;
  --text-unit: px;
  font-size: var(--text-size)var(--text-unit); /* Invalid, as it does not resolve to 12px */

  /* 5. */
  --initialized: initial;
  background: var(--initialized, initial); /* Results in background: initial */

  /* 6. */
  --invalid-url: "https://useme.medium.com";
  background: url(var(--invalid-url)); /* Invalid, as url() cannot parse var() */

  --valid-url: url(https://useme.medium.com);
  background: var(--valid-url); /* Correct usage */
}

Variable Resolution and Scope

CSS variables, like other CSS properties, follow CSS-specific rules for scope and specificity. Understanding how these factors affect CSS variables allows for more precise control.

Global and Scoped Variables:
Variables defined in :root are applied globally, while those defined in selectors have a more limited scope.

   :root {
     --main-color: blue; /* Globally applied */
   }

   .container {
     --main-color: green; /* Scoped, applies only within .container */
   }

Priority by Specificity:
Higher specificity will override lower specificity for CSS variables.

   :root {
     --main-color: blue;
   }

   .section {
     --main-color: green; /* Overrides :root definition */
   }

   .section p {
     color: var(--main-color); /* Shows green */
   }

   p {
     color: var(--main-color); /* Shows blue */
   }
   <div>



<p><strong>Calculating Values Based on Specificity Order:</strong> <br>
Like CSS properties, variables are resolved based on specificity in ascending order.<br>
</p>

<pre class="brush:php;toolbar:false">   :root {
     --red: 255;
     --green: 255;
     --blue: 255;
     --background: rgb(var(--red), var(--green), var(--blue));
   }

   .box {
     --green: 0;
     background: var(--background); 
   }

In this example, the background color of .box remains white, as --background was resolved to rgb(255, 255, 255) before .box redefined --green: 0.

Reevaluating Variables with Pseudo-Classes:
Variables change based on pseudo-class states when defined at the same level.

   :root {
     --red: 255;
     --green: 255;
     --blue: 255;
   }

   .box {
     --background: rgb(var(--red), var(--green), var(--blue));
     background: var(--background);
   }

   .box:hover {
     --green: 0; /* Changes background color on hover */
   }

Next, let’s explore some advanced use cases for CSS variables:

Usage Example A: Animations

CSS variables cannot be directly animated because the browser cannot infer the data type. To resolve this, use @property to define the variable's type and initial value, enabling the browser to understand how to animate the variable.

@property --green {
  syntax: "<number>";
  initial-value: 255;
  inherits: false;
}

.section {
  padding: 5em;
  background: rgb(50, var(--green), 50);
  transition: --green 0.5s;
}

.section:hover {
    --green: 50;
}
</number>
<div>



<p>In this example, @property is used to declare --green as a <number> type with an initial value of 255. When hovering over .section, --green changes to 50, creating a smooth color transition effect.</number></p>

<p>CodePen example</p>


<hr>

<h2>
  
  
  Usage Example B: Light/Dark Mode Toggle
</h2>

<p>If you want to implement theme switching for light and dark modes, it’s helpful to extract color values into variables that adjust automatically based on the prefers-color-scheme setting. Here’s how you can manage this using CSS variables.<br>
</p>

<pre class="brush:php;toolbar:false">:root {
  --background-color: #FBFBFB;
  --container-background-color: #EBEBEB;
  --headline-color: #0077EE;
  --text-color: #333333;
}

@media (prefers-color-scheme: dark) {
  :root {    
    --background-color: #121212;
    --container-background-color: #555555;
    --headline-color: #94B2E6;
    --text-color: #e0e0e0;
  }
}

Adding a Manual Toggle that Aligns with System Preferences

While the system setting controls the theme by default, we may want to give users the option to manually toggle between light and dark themes. To achieve this, we can add a checkbox to toggle the state. Ideally, when the checkbox is selected, it indicates dark mode, and when unselected, it represents light mode.

However, CSS cannot automatically detect system settings and change the checkbox state accordingly, especially in dark mode. To handle this limitation, we can use CSS variables and the :has() selector to control theme switching based on the checkbox state.

I wanted to try achieving this entirely with CSS, but since a user’s system may be set to either light or dark mode, CSS alone can’t automatically check the checkbox in dark mode.

If we can’t move the mountain, we’ll route the path. Here’s the workaround:

  • We’ll use CSS to create a toggle switch, where the visual “OFF” state represents light mode, and “ON” represents dark mode.

The Surprising Details of CSS Variables - Using var() and Cool Examples
The Surprising Details of CSS Variables - Using var() and Cool Examples

  • When system sets to light mode: When the checkbox is unselected, it corresponds to the “OFF” state (light mode). When selected, it corresponds to the “ON” state (dark mode).

  • When system sets to dark mode: Since the system preference is reversed, the visual state also inverts. When the checkbox is unselected, it corresponds to “ON” (dark mode). When selected, it corresponds to “OFF” (light mode).

To achieve this effect, we need two main elements:

First: Variables that Change Based on System Setting and Checkbox State

:root {
  --background-color: #FBFBFB;
  --container-background-color: #EBEBEB;
  --headline-color: #0077EE;
  --text-color: #333333;
}

:root:has(input[type="checkbox"]:checked) {
  --background-color: #121212;
  --container-background-color: #555555;
  --headline-color: #94B2E6;
  --text-color: #e0e0e0;
}

@media (prefers-color-scheme: dark) {
  :root {    
    --background-color: #121212;
    --container-background-color: #555555;
    --headline-color: #94B2E6;
    --text-color: #e0e0e0;
  }

  :root:has(input[type="checkbox"]:checked) {
    --background-color: #FBFBFB;
    --container-background-color: #EBEBEB;
    --headline-color: #0077EE;
    --text-color: #333333;
  }
}

Second: Toggle Behavior Based on System Settings for checked State and ON/OFF Representation

The light and dark mode CSS properties are reversed depending on the system setting.

/* Toggle Switch Styles */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* Hide the checkbox element to style a custom switch */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* Slider styling for the switch background */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--slider-bg, #ccc);
  transition: 0.4s;
  border-radius: 34px;
}

/* Slider knob styling */
.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50%;
}

/* Dark mode styles: make the switch look "checked" by default */
@media (prefers-color-scheme: dark) {
  .slider {
    background-color: #94b2e6;
  }
  .slider:before {
    transform: translateX(26px); /* Move knob to the right */
  }

  /* Invert checked state in dark mode to look "unchecked" */
  input:checked + .slider {
    background-color: #ccc;
  }
  input:checked + .slider:before {
    transform: translateX(0); /* Move knob to the left */
  }
}

/* Light mode styles: make the switch look "unchecked" by default */
@media (prefers-color-scheme: light) {
  .slider {
    background-color: #ccc;
  }
  .slider:before {
    transform: translateX(0); /* Knob on the left */
  }

  /* Invert checked state in light mode to look "checked" */
  input:checked + .slider {
    background-color: #94b2e6;
  }
  input:checked + .slider:before {
    transform: translateX(26px); /* Move knob to the right */
  }
}

Simplifying Variable Setup with CSS Variable Tricks

Here we’ll use Space Toggle technique to simplify variable settings. Here’s the code, followed by an explanation of how it works:

:root {
  --ON: initial; /* Default state variable to use for switching colors */
  --OFF: ; /* Alternative state variable for switching colors */

  /* Set default color variables based on light mode */
  --light: var(--ON);
  --dark: var(--OFF);

  /* Define custom properties for colors used in light and dark modes */
  --background-color: var(--light, #fbfbfb) var(--dark, #121212);
  --container-background-color: var(--light, #ebebeb) var(--dark, #555555);
  --headline-color: var(--light, #0077ee) var(--dark, #94b2e6);
  --text-color: var(--light, #333333) var(--dark, #e0e0e0);
}

:root:has(input[type="checkbox"]:checked) {
  --light: var(--OFF);
  --dark: var(--ON);
}

The key here is in the line --background-color: var(--light, #fbfbfb) var(--dark, #121212);. Here, the background color depends on the values of --light and --dark, effectively simulating an if/else in the property.

How does it work? Initially, --light: var(--ON); and --ON: initial; make --ON an invalid state. Meanwhile, --OFF is set as an empty string. When applied to var(--light, #fbfbfb) var(--dark, #121212), the invalid --light variable will default to #fbfbfb, and the valid --dark variable (empty) allows --background-color to equal #fbfbfb.

All the other color variables follow the same logic, adjusting based on the state of --light and --dark. This way, each color variable only needs to be defined once.

Switching states becomes simple. If dark mode is active, use --light: var(--OFF); and --dark: var(--ON);. In light mode, reverse them. Though not immediately intuitive, this method is currently the most effective with CSS. If there are better solutions, they are worth exploring.

Complete example: CodePen Example


Summary

CSS continues to evolve, with CSS variables available in major browsers since 2016. New features like @property and :has() are expanding CSS variables’ flexibility even further. Combined with other new tools, CSS variables are becoming more powerful—for instance, they can now enhance scroll-driven animations to create visually dynamic effects. As a core element for storing state in CSS, much like variables in any programming language, a solid understanding of CSS variables will prove invaluable for more sophisticated styling and design down the road.


References

  • https://stackoverflow.com/questions/42330075/is-there-a-way-to-interpolate-css-variables-with-url/42331003#42331003
  • https://kizu.dev/cyclic-toggles/#was-this-always-possible
  • https://dev.to/afif/what-no-one-told-you-about-css-variables-553o
  • https://hackernoon.com/cool-css-variable-tricks-to-try-uyu35e9
  • https://lea.verou.me/blog/2020/10/the-var-space-hack-to-toggle-multiple-values-with-one-custom-property/

以上是CSS 變數的驚人細節 - 使用 var() 和很酷的範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
CSS計數器:自動編號的綜合指南CSS計數器:自動編號的綜合指南May 07, 2025 pm 03:45 PM

CSSCOUNTERSAREDOMANAGEAUTOMANAMBERINGINWEBDESIGNS.1)他們可以使用forterablesofcontents,ListItems,and customnumbering.2)AdvancedsincludenestednumberingSystems.3)挑戰挑戰InclassINCludeBrowsEccerCerceribaliblesibility andperformiballibility andperformissises.4)創造性

使用捲軸驅動動畫的現代滾動陰影使用捲軸驅動動畫的現代滾動陰影May 07, 2025 am 10:34 AM

使用滾動陰影,尤其是對於移動設備,是克里斯以前涵蓋的一個微妙的UX。傑夫(Geoff)涵蓋了一種使用動畫限制屬性的新方法。這是另一種方式。

重新訪問圖像圖重新訪問圖像圖May 07, 2025 am 09:40 AM

讓我們快速進修。圖像地圖一直返回到HTML 3.2,首先是服務器端地圖,然後使用映射和區域元素通過圖像上的單擊區域定義了可單擊區域。

DEV狀態:每個開發人員的調查DEV狀態:每個開發人員的調查May 07, 2025 am 09:30 AM

開發委員會調查現已開始參與,並且與以前的調查不同,它涵蓋了除法:職業,工作場所,以及健康,愛好等。 

什麼是CSS網格?什麼是CSS網格?Apr 30, 2025 pm 03:21 PM

CSS網格是創建複雜,響應式Web佈局的強大工具。它簡化了設計,提高可訪問性並提供了比舊方法更多的控制權。

什麼是CSS Flexbox?什麼是CSS Flexbox?Apr 30, 2025 pm 03:20 PM

文章討論了CSS FlexBox,這是一種佈局方法,用於有效地對齊和分佈響應設計中的空間。它說明了FlexBox用法,將其與CSS網格進行了比較,並詳細瀏覽了瀏覽器支持。

我們如何使用CSS使網站迅速響應?我們如何使用CSS使網站迅速響應?Apr 30, 2025 pm 03:19 PM

本文討論了使用CSS創建響應網站的技術,包括視口元標籤,靈活的網格,流體媒體,媒體查詢和相對單元。它還涵蓋了使用CSS網格和Flexbox一起使用,並推薦CSS框架

CSS盒裝屬性有什麼作用?CSS盒裝屬性有什麼作用?Apr 30, 2025 pm 03:18 PM

本文討論了CSS盒裝屬性,該屬性控制了元素維度的計算方式。它解釋了諸如Content-Box,Border-Box和Padding-Box之類的值,以及它們對佈局設計和形式對齊的影響。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器