首页  >  文章  >  web前端  >  CSS 变量的惊人细节 - 使用 var() 和很酷的示例

CSS 变量的惊人细节 - 使用 var() 和很酷的示例

Barbara Streisand
Barbara Streisand原创
2024-11-15 05:49:02523浏览

CSS 변수 포스팅 후반부, 전반부는 여기까지입니다.
이번 글에서는 var()의 세부사항을 살펴보겠습니다. 그리고 두 가지 멋진 예:

  • CSS 변수를 이용한 애니메이션
  • 시스템 설정 감지 기능을 갖춘 순수 CSS 다크 모드 토글

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

var() 사용

var()는 사용자 정의 속성 값(CSS 변수)에 액세스합니다. 구문은 다음과 같습니다.

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

기본 규칙

  1. 첫 번째 매개변수는 CSS 변수여야 합니다. var(20px)와 같은 직접적인 값은 오류가 발생합니다. var()는 사용자 정의 속성 이름만 허용하기 때문입니다.

  2. var()는 속성 이름을 대체할 수 없습니다. 즉, var(--prop-name): 20px; var()는 속성 값에만 사용하도록 제한되어 있기 때문입니다.

.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 */
}

상세한 행동

  1. var(--b, fallback_value) 폴백: 두 번째 매개변수는 --b가 유효하지 않은 경우 사용되는 폴백 값 역할을 합니다.

  2. var(--c,) 빈 대체 구문: 대체 값이 비어 있는 경우 구문은 유효한 상태로 유지되며 --c가 유효하지 않은 경우 기본적으로 빈 값이 사용됩니다. .

  3. 여러 쉼표: var(--d, var(--e), var(--f), var(--g))에서 첫 번째 쉼표 뒤의 모든 내용은 다음과 같습니다. 폴백으로 처리되므로 --d가 유효하지 않은 경우 var() 표현식은 var(--e), var(--f), var(--g)를 하나의 폴백으로 평가합니다. 결과를 결정합니다.

  4. 완전한 CSS 토큰으로서의 var(): 이 함수는 20px처럼 완전한 CSS 토큰 역할을 합니다. 따라서 var(--size)var(--unit)은 20px을 생성하지 않으며 유효하지 않은 것으로 간주됩니다.

  5. CSS 변수에 이니셜 사용: CSS 변수에 이니셜을 할당하면 해당 변수가 유효하지 않음을 의미합니다. 이니셜을 값으로 표시하려면 fallback에 배치해야 합니다.

  6. url() 및 var() 사용법: url()은 완전한 CSS 토큰으로 처리되므로 변수 내에서 전체 url()을 정의해야 합니다.

: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 */
}

가변 해상도 및 범위

CSS 변수는 다른 CSS 속성과 마찬가지로 범위 및 구체성에 대한 CSS 관련 규칙을 따릅니다. 이러한 요소가 CSS 변수에 어떤 영향을 미치는지 이해하면 보다 정확한 제어가 가능합니다.

전역 및 범위 변수:
:root에 정의된 변수는 전역적으로 적용되는 반면, 선택자에 정의된 변수는 범위가 더 제한적입니다.

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

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

구체성에 따른 우선순위:
더 높은 특이성은 CSS 변수에 대한 더 낮은 특이성을 덮어씁니다.

   :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); 
   }

이 예에서 .box가 --green: 0으로 재정의되기 전에 -- background가 rgb(255, 255, 255)로 확인되었으므로 .box의 배경색은 흰색으로 유지됩니다.

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;
}
<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.

<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