阿里云主机折上折
  • 微信号
Current Site:Index > Definition and usage of variables

Definition and usage of variables

Author:Chuan Chen 阅读数:10917人阅读 分类: CSS

Definition and Usage of Variables

Variables in CSS, also known as custom properties, allow developers to define reusable values in stylesheets. These variables can be referenced and modified throughout the document, improving code maintainability and flexibility. By using variables, repetitive code can be reduced, theme switching simplified, and dynamic style adjustments achieved.

Basic Syntax of Variables

CSS variables start with two hyphens (--), followed by the variable name. Variable names are case-sensitive and can include letters, numbers, hyphens, and underscores. When defining variables, they are typically placed in the :root pseudo-class to make them global:

:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --font-size-base: 16px;
}

Local variables can be defined within any selector:

.container {
  --padding: 20px;
  --border-radius: 8px;
}

Using Variables

Use the var() function to reference variables:

.button {
  background-color: var(--primary-color);
  padding: var(--padding);
  border-radius: var(--border-radius);
}

If a variable is undefined, a fallback value can be provided:

.element {
  color: var(--undefined-color, #333);
  font-size: var(--undefined-size, 16px);
}

Variable Scope

CSS variables follow cascading rules, and child elements can inherit variable values from their parent:

:root {
  --text-color: #333;
}

body {
  color: var(--text-color);
}

.dark-theme {
  --text-color: #fff;
}

Local variables override global variables:

:root {
  --spacing: 10px;
}

.special-section {
  --spacing: 20px;
  padding: var(--spacing);
}

Dynamic Modification of Variables

CSS variables can be dynamically modified using JavaScript:

document.documentElement.style.setProperty('--primary-color', '#e74c3c');

This makes it possible to implement theme switching without reloading the page:

function toggleTheme() {
  const root = document.documentElement;
  const currentTheme = root.style.getPropertyValue('--theme') || 'light';
  
  if (currentTheme === 'light') {
    root.style.setProperty('--bg-color', '#222');
    root.style.setProperty('--text-color', '#fff');
    root.style.setProperty('--theme', 'dark');
  } else {
    root.style.setProperty('--bg-color', '#fff');
    root.style.setProperty('--text-color', '#333');
    root.style.setProperty('--theme', 'light');
  }
}

Advanced Usage of Variables

CSS variables can be used for calculations:

:root {
  --base-size: 16px;
  --large-size: calc(var(--base-size) * 1.5);
}

Variables can be combined:

:root {
  --primary: #3498db;
  --primary-light: color-mix(in srgb, var(--primary), white 20%);
}

Using variables in media queries:

:root {
  --gutter: 10px;
}

@media (min-width: 768px) {
  :root {
    --gutter: 20px;
  }
}

Practical Applications of Variables

Creating a responsive grid system:

:root {
  --columns: 12;
  --gutter: 15px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(var(--columns), 1fr);
  gap: var(--gutter);
}

@media (max-width: 768px) {
  :root {
    --columns: 6;
  }
}

Implementing theme switching:

:root {
  --bg-color: #fff;
  --text-color: #333;
  --accent-color: #3498db;
}

.dark-mode {
  --bg-color: #222;
  --text-color: #fff;
  --accent-color: #e74c3c;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

a {
  color: var(--accent-color);
}

Performance Considerations for Variables

While CSS variables are highly useful, the following points should be noted:

  1. Overuse of variables may slow down style calculations
  2. Dynamic modification of variables triggers repaints and reflows
  3. In large projects, variable naming should remain consistent

Browser Support for Variables

Modern browsers offer good support for CSS variables:

  • Chrome 49+
  • Firefox 31+
  • Safari 9.1+
  • Edge 15+
  • Opera 36+

For older browsers that do not support CSS variables, the @supports rule can provide fallbacks:

.element {
  color: #333; /* Fallback value */
}

@supports (--css: variables) {
  .element {
    color: var(--text-color);
  }
}

Differences Between Variables and Preprocessor Variables

CSS variables differ fundamentally from preprocessor variables like Sass/Less:

  1. CSS variables run in the browser, while preprocessor variables are processed during compilation
  2. CSS variables can be dynamically modified, while preprocessor variables are fixed after compilation
  3. CSS variables follow DOM structure and have scope concepts
// Sass variables (processed during compilation)
$primary-color: #3498db;

.button {
  background-color: $primary-color;
}
/* CSS variables (processed at runtime) */
:root {
  --primary-color: #3498db;
}

.button {
  background-color: var(--primary-color);
}

Debugging Techniques for Variables

CSS variables can be inspected and modified in developer tools:

  1. In Chrome DevTools' Elements panel, inspect the :root or specific elements' styles
  2. Search for -- in the Computed panel to find all used variables
  3. Modify variable values directly in the Styles panel for real-time debugging

Naming Conventions for Variables

Good variable naming improves code readability:

  1. Use meaningful names, such as --header-height instead of --hh
  2. Maintain naming consistency, such as all lowercase or kebab-case
  3. Consider using prefixes to indicate variable purpose, such as --color-primary or --spacing-md
  4. Avoid overly specific names, such as --button-red-color, which should be --color-accent

Handling Units in Variables

CSS variables can store values with or without units:

:root {
  --spacing: 12;
  --spacing-px: calc(var(--spacing) * 1px);
}

.box {
  padding: var(--spacing-px);
}

This approach allows for unit conversion when needed:

:root {
  --base-size: 16;
}

.element {
  font-size: calc(var(--base-size) * 1px);
  margin: calc(var(--base-size) * 0.5rem);
}

Inheritance Characteristics of Variables

CSS variables inherit values from parent elements but do not automatically inherit into pseudo-elements:

:root {
  --tooltip-color: #333;
}

.tooltip::before {
  /* Explicit inheritance required */
  color: var(--tooltip-color);
}

Inheritance can be forced using the inherit keyword:

.tooltip::before {
  color: inherit;
}

Handling Invalid Variable Values

When a variable value is invalid, the browser ignores the declaration:

:root {
  --bg-color: 20px; /* Invalid color value */
}

.box {
  background-color: var(--bg-color, #f0f0f0); /* Fallback value used */
}

Combining Variables with CSS Functions

CSS variables can be combined with various CSS functions:

:root {
  --hue: 200;
  --saturation: 50%;
  --lightness: 60%;
}

.element {
  background-color: hsl(var(--hue), var(--saturation), var(--lightness));
  transform: rotate(calc(var(--angle) * 1deg));
}

Modular Use of Variables

In large projects, variables can be organized into separate files:

/* variables.css */
:root {
  /* Colors */
  --color-primary: #3498db;
  --color-secondary: #2ecc71;
  
  /* Spacing */
  --spacing-sm: 8px;
  --spacing-md: 16px;
  
  /* Fonts */
  --font-size-base: 16px;
}

Then import them in the main stylesheet:

@import "variables.css";

body {
  font-size: var(--font-size-base);
}

Application of Variables in Responsive Design

Combine CSS variables with media queries to create responsive designs:

:root {
  --font-size: 16px;
  --gutter: 10px;
}

@media (min-width: 768px) {
  :root {
    --font-size: 18px;
    --gutter: 20px;
  }
}

@media (min-width: 1024px) {
  :root {
    --font-size: 20px;
    --gutter: 30px;
  }
}

Animation Applications of Variables

CSS variables can be used to create dynamic animations:

:root {
  --rotate: 0;
}

.spinner {
  transform: rotate(calc(var(--rotate) * 1deg));
  transition: transform 0.3s ease;
}

.spinner:hover {
  --rotate: 180;
}

Control animations with JavaScript:

function animateSpinner() {
  let rotation = 0;
  setInterval(() => {
    rotation += 5;
    document.documentElement.style.setProperty('--rotate', rotation);
  }, 50);
}

Future Development of Variables

CSS variables are continuously evolving, with potential future support for:

  1. Type checking: Ensuring variable values match expected types
  2. More complex scoping rules
  3. Deeper integration with CSS Houdini APIs
  4. More flexible usage in @keyframes

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.