A Deeper Understanding of CSS Variables: Advanced Tips and Best Practices

Preface

CSS variables are a powerful feature that can help developers better organize and manage style sheets. In this article, we’ll dive into advanced tips and best practices for CSS variables. By learning how to use variables as calculated values, media queries, and dynamic changes, you’ll be able to better take advantage of the power of CSS variables.


1. Concept

CSSA variable (also called a custom property) is a CSSvalue defined and used in a that can be reused throughout a stylesheet. They provide a flexible way to store and manage values ​​in styles, making style modifications easier and more maintainable.


2. Basic usage

CSSThe basic usage of variables includes defining variables, using variables and modifying the values ​​of variables.

1. Define variables

In CSS, variables are defined using the – prefix. Variable names can consist of letters, numbers, dashes, and underscores, but they must begin with a letter. Variable definitions are usually placed within the selector's rule set, or :rootdefined in the root element ( ) for global use. For example:

:root {
    
    
  --primary-color: #ff0000;
  --font-size: 16px;
}

2. Use variables

When using variables, you need to var()wrap the variables with functions. Variables can be used anywhere CSSa property value can be used, such as color, size, margin, etc. For example:

.element {
    
    
  color: var(--primary-color);
  font-size: var(--font-size);
}

3. Modify the value of the variable

The value of the variable can be CSSdynamically modified in to achieve style changes. The value of a variable can be modified via JavaScript or using pseudo-classes ( :hover, :focusetc.). For example:

.element:hover {
    
    
  --primary-color: #00ff00;
}

Or use JavaScriptto modify the value of a variable:

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

3. Naming convention

When we CSSuse variables in , in order to avoid conflicts with existing CSSproperties, we can use custom CSSvariables and choose appropriate naming conventions for them. Properties starting with two dashes ( --) are considered CSSvariables.

Here are some common CSSvariable naming conventions:

  • Use meaningful names: To increase code readability and maintainability, we should choose descriptive names for CSSvariables. This makes it easier for other developers to understand the purpose and meaning of the variables;
  • Use lowercase letters and hyphens: CSSVariable names should be in lowercase letters and use hyphens ( -) as separators between words. For example, --primary-color;
  • Use namespaces: To avoid conflicts with other variables, you can use namespaces to group variables. For example, --button-primary-color, where buttonis the namespace;
  • Avoid using abbreviations and abbreviations: Try to avoid using abbreviations and abbreviations for variable names as this may make the code less readable. Choose descriptive names so that other developers can easily understand what the variable means;
  • Use a consistent naming convention: It is important to maintain a consistent naming convention throughout your project. Choosing a naming style and sticking to it throughout your project will improve code consistency and readability.

In short, CSSvariable naming conventions should focus on readability, maintainability, and consistency. We can better organize and manage our variables by choosing meaningful names, using lowercase letters and hyphens, using namespaces, and avoiding abbreviations and abbreviations CSS.


4. Variable value type

In CSS, CSSthe values ​​of variables can be of various types. Different types will also have subtle differences in usage.

If the variable value is a string, it can be concatenated with other strings, for example:

<!DOCTYPE html>
<html>

<style>
  :root {
      
      
    --primary-content: 'hello';
  }


  .box:after {
      
      
    content: '标题 : ' var(--primary-content)
  }
</style>

<body>
  <div class="box"></div>
</body>

</html>
  • achieve effect

Insert image description here

If the variable value is a numeric value, it cannot be used directly with the numeric unit, for example:

In the code below, we box2use calc()the function in the box to perform a mathematical calculation, multiplying --primary-numthe value of the variable 1by pixels ( 1px). This way, you can combine values ​​with units to achieve the correct styling effect. In this way, we can splice values ​​and units to ensure the correctness of the style. And calc()functions can perform more complex mathematical calculations, such as addition, subtraction, multiplication, division, etc.

<!DOCTYPE html>
<html>

<style>
  :root {
      
      
    --primary-num: 40;
  }

  .box1 {
      
      
    background: cadetblue;
    padding-top: var(--primary-num)px;
  }

  .box2 {
      
      
    background: chocolate;
    padding-top: calc(var(--primary-num) * 1px);
  }
</style>

<body>
  <div class="box1">内容1</div>
  <div class="box2">内容2</div>
</body>

</html>
  • achieve effect

Insert image description here

If the variable value has a unit, it cannot be written as a string, for example:

In the code below, we box1define the variable value with units as a string in the box. This is invalid because CSSthe attribute expects a numeric unit, not a string. Such a definition will cause the style to be invalid or produce an error. Therefore, when a variable value has a unit, it should be defined as a numeric value, not a string. This ensures that variables CSSare correctly combined with units when applied to properties.

<!DOCTYPE html>
<html>

<style>
  :root {
      
      
    --border-radius-box1: '20px';
    --border-radius-box2: 20px;
  }

  .box1 {
      
      
    background: chocolate;
    border-radius: var(--border-radius-box1);
  }

  .box2 {
      
      
    background: cornflowerblue;
    border-radius: var(--border-radius-box2);
  }
</style>

<body>
  <div class="box1">内容1</div>
  <div class="box2">内容2</div>
</body>

</html>
  • achieve effect

Insert image description here


5. How to understand: root and var()

:rootPseudo class:

  • :rootPseudo-class selectors match the root element of the document tree, usually <html>the element;
  • :rootVariables defined in pseudo-classes CSScan be used globally throughout the document;
  • By :rootdefining variables in pseudo-classes, we can set global CSSattribute values ​​for the entire document;
  • For example, we can use :rootpseudo-classes to define global colors, font sizes, breakpoint values, etc.

var()function:

  • var()Functions are used to reference and use CSSthe value of variables;
  • It accepts one parameter, which is the name of the variable to be referenced CSS;
  • var()Functions can CSSbe used on the value of any property, including font size, color, margins, etc.;
  • By using var()functions, we can use the same variable value in different elements and selectors as needed CSSto achieve unified style management;
  • For example, we can use var(--primary-color)to refer to a globally defined --primary-colorvariable.

CSSThis is the basic usage of variables. By defining, using and modifying the values ​​of variables, style reuse, dynamic changes and global control can be achieved. This makes CSSdevelopment more flexible and maintainable. Three cases are provided below, covering the complete code of examples of defining variables, using variables, and modifying the values ​​of variables.

Case 1

In this case, we define two variables --primary-colorand --font-sizeand apply them to .elementthe color and font size of the element. When the mouse is hovering .elementover the element, --primary-colorthe value of the variable will turn green and --font-sizethe value of the variable will become 26px.

<!DOCTYPE html>
<html>

<head>
  <style>
    :root {
      
      
      --primary-color: #f88604;
      --font-size: 22px;
    }

    .element {
      
      
      color: var(--primary-color);
      font-size: var(--font-size);
    }

    .element:hover {
      
      
      --primary-color: rgb(0, 104, 202);
    }
  </style>
</head>

<body>
  <div class="element">Hello, CSS Variables!</div>
</body>

</html>
  • achieve effect

Insert image description here


Case 2

In this case, we use JavaScriptto monitor window size changes and dynamically modify CSSthe value of the custom property based on the window width. In updateStylesthe function, we window.getComputedStyleobtain --breakpointthe value of through the method, and determine whether to apply responsive styles based on the window width.

<!DOCTYPE html>
<html>

<head>
  <style>
    :root {
      
      
      --breakpoint: 300px;
      --font-size: 16px;
      --primary-color: #ff0000;
    }

    .element {
      
      
      font-size: var(--font-size);
      color: var(--primary-color);
    }
  </style>
  <script>
    function updateStyles() {
      
      
      var element = document.querySelector('.element');
      var breakpoint = getComputedStyle(document.documentElement).getPropertyValue('--breakpoint');

      if (window.innerWidth <= parseInt(breakpoint)) {
      
      
        element.style.setProperty('--font-size', '14px');
        element.style.setProperty('--primary-color', '#00ff00');
      } else {
      
      
        element.style.setProperty('--font-size', '16px');
        element.style.setProperty('--primary-color', '#ff0000');
      }
    }

    window.addEventListener('resize', updateStyles);
    window.addEventListener('DOMContentLoaded', updateStyles);
  </script>
</head>

<body>
  <div class="element">Responsive Text</div>
</body>

</html>
  • achieve effect

Insert image description here


Case 3

In this case, we define a variable --primary-colorand apply it to .elementthe color of the element. Through the function JavaScriptin changeColor, we can modify the value of the variable by clicking the button --primary-color, thereby changing .elementthe color of the element.

<!DOCTYPE html>
<html>

<head>
  <style>
    :root {
      
      
      --primary-color: orange;
    }

    .element {
      
      
      color: var(--primary-color);
    }
  </style>
  <script>
    function changeColor() {
      
      
      document.documentElement.style.setProperty('--primary-color', 'blue');
      // document.documentElement.style.setProperty('root变量', '更改的值')
    }
  </script>
</head>

<body>
  <div class="element">Click the button to change color</div>
  <button onclick="changeColor()">点击改变颜色</button>
</body>

</html>
  • achieve effect

Insert image description here


Case 4

In this case, by using CSSvariables, we can dynamically control the style of the button and achieve the mouse tracking effect.
In the code, we define two CSSvariables: --xand --y. These two variables represent the abscissa and ordinate of the mouse on the button respectively. Through the method JavaScriptin setProperty, we can update the values ​​of these two variables in real time based on the position of the mouse movement event. section SCSS, we use these two CSSvariables to determine the position of the mouse tracking effect. By applying --xand to the and attributes of --ythe pseudo-element , we can make the pseudo-element follow the mouse position. In addition, we also use variables to control the size of pseudo-elements. When the mouse hovers over the button, by changing the value, we can achieve a gradient background animation effect.::beforelefttopCSS--size--size

<template>
  <div class="track-btn" @mousemove="handleMouseMove">
    <span>使用 CSS 变量让你的按钮更炫酷</span>
  </div>
</template>

<script>
export default {
      
      
  methods: {
      
      
    handleMouseMove(e) {
      
      
      const btnStyle = e.target.style;
      btnStyle.setProperty("--x", `${ 
        e.offsetX}px`);
      btnStyle.setProperty("--y", `${ 
        e.offsetY}px`);
    },
  },
};
</script>

<style lang="scss">
.track-btn {
      
      
  position: relative;
  width: 400px;
  height: 50px;
  background-color: rgb(102, 219, 255);
  cursor: pointer;
  line-height: 50px;
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  color: #fff;
  overflow: hidden;

  span {
      
      
    position: relative;
    pointer-events: none;
  }

  &::before {
      
      
    --size: 0;
    position: absolute;
    left: var(--x);
    top: var(--y);
    width: var(--size);
    height: var(--size);
    background-image: radial-gradient(
      circle closest-side,
      rgb(0, 215, 82),
      transparent
    );
    content: "";
    transform: translate3d(-50%, -50%, 0);
    transition: width 200ms ease, height 200ms ease;
  }

  &:hover::before {
      
      
    --size: 400px;
  }
}
</style>
  • achieve effect

Insert image description here


6. Variable scope

CSSThe scope of variables is the scope of the selector that defines them. Variables defined within a selector can only be used within that selector, while variables defined in the global scope can be used throughout the document.

1. Global scope

  • :rootVariables defined in pseudo-classes have CSSglobal scope;
  • :rootPseudo-class selectors match the root element of the document tree, usually <html>the element;
  • Variables defined in :rootpseudo-classes can be used globally throughout the document.
<!DOCTYPE html>
<html>

<head>
  <style>
    :root {
      
      
      --bg-color: rgb(88, 88, 186);
      --color: #33ca63;
    }

    div {
      
      
      background-color: var(--bg-color);
      color: var(--color);
    }

    span {
      
      
      background-color: var(--bg-color);
      color: var(--color);
    }
  </style>
</head>

<body>
  <div>
    <p>我在div内部</p>
  </div>
  <span>我在div外部</span>
</body>

</html>
  • achieve effect

Insert image description here


2. Local scope

  • Variables defined inside a selector or element CSShave local scope;
  • These variables can only be used inside the selector or element in which they are defined;
  • Variables in the local scope override variables with the same name in the global scope.
<!DOCTYPE html>
<html>

<head>
  <style>
    div {
      
      
      --bg-color: rgb(88, 88, 186);
      --color: #33ca63;
    }

    p {
      
      
      background-color: var(--bg-color);
      color: var(--color);
    }

    span {
      
      
      background-color: var(--bg-color);
      color: var(--color);
    }
  </style>
</head>

<body>
  <div>
    <p>我在div内部</p>
  </div>
  <span>我在div外部</span>
</body>

</html>
  • achieve effect

Insert image description here


3. Set scoped in vue

In , when you add the attribute vueto the component's tag , the style will be scoped to the component. This means that only elements within the current component will be affected by these styles and will not leak to other components. However, the behavior of variables in styles is different from normal selector styles. When you use the attribute in a tag, a unique class name is automatically added to the root element of each component to ensure that the component's styles are only applied inside that component. Since the variable is global, its scope will exceed the scope of the component. So in a component with a style , variables are not effective in other components. In other words, you cannot use variables defined in one component in other components.<style>scopedCSSCSSvuescoped<style>scopedvueCSSscopedvueCSSCSS

If you want to vueshare variables between components CSS, there are two common methods:

  1. Use CSSpreprocessors such as Sassor Less, which can provide variable scoping and sharing capabilities;
  2. Define CSSthe variable in a global style (without using scopedthe attribute) so it is shared across all components.

It should be noted that if you choose to CSSdefine variables in a global style, please ensure that the naming of the variables is unique to avoid possible conflicts.


7. Variable priority

CSSVariables CSShave the same priority as other attributes, following CSScascading rules. Here is CSSthe general order of attribute priority (from highest to lowest):

  • !important: !importantThe style declared using has the highest priority and will override all other styles;
  • Inline styles: Styles defined directly HTMLusing the attribute on the element stylehave higher priority;
  • IDSelector: IDStyles defined using selectors have higher priority;
  • Class selectors, attribute selectors and pseudo-class selectors: The styles defined by these selectors have medium priority;
  • Element selectors and pseudo-element selectors: The styles defined by these selectors have lower priority;
  • Inherited styles: Styles inherited from parent elements have the lowest priority.

When variables are involved CSS, they have the same precedence as other selectors. If multiple identical CSSvariables are defined on the same element, the variables defined later will overwrite the previous variables. If the same variable is defined in different selectors CSS, the selector precedence rules are followed. For example, if a variable is defined in an inline style CSS, it will have higher priority and will override the same variable defined in other selectors. Likewise, if IDa variable is defined in a selector CSS, it will have higher priority and will override the same variable defined in other selectors.

<!DOCTYPE html>
<html>

<head>
  <style>
    :root {
      
      
      --primary-color: blue;
    }

    .container {
      
      
      --primary-color: red;
    }

    .box {
      
      
      background-color: var(--primary-color);
      width: 200px;
      height: 200px;
      margin: 20px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="box"></div>
  </div>
</body>

</html>

In this case, we defined a variable called --primary-colorand CSSset :rootit to blue in the pseudo-class. Then, .containerthe same variable was redefined in the class selector and set to red. In .boxthe class selector, we use var()the function to reference --primary-colorthe variable and use it as the background color. Since .containerthe class selector has higher priority, the final .boxbackground color will be red.

  • achieve effect

Insert image description here


8. Compatibility

CSSVariables actually have good compatibility in modern browsers, but there may be some limitations in some older versions of browsers.

Browser compatibility
Chrome Supports Chrome 49versions from and above
Firefox Supports Firefox 31versions from and above
Safari Supports Safari 9.1versions from and above
Opera Supports Opera 36versions from and above
Edge Supports Edge 15versions from and above
Internet Explorer CSSVariables are not supported

9. Improvements brought about by using CSS variables

  • Reusability and ease of maintenance

    CSSVariables allow you to define a style once and reuse it multiple times throughout the style sheet. This can reduce code duplication and improve code maintainability. By modifying the value of a variable, you can easily change the appearance of an entire style without having to modify each specific style individually.

  • Dynamic and flexible

    CSSVariables can be modified dynamically at runtime without modifying the stylesheet. This makes it easier to apply different styles under different conditions. For example, you can achieve dynamic style changes by changing the value of a variable based on user selection or theme switching.

  • Responsive design

    CSSVariables can be used in conjunction with media queries to achieve responsive design. By defining different variable values ​​in different media queries, you can adjust styles based on the device's screen size and characteristics. This allows web pages to adapt to different screen sizes and device types, providing a better user experience.

  • Readability and maintainability

    CSSVariables can be defined with meaningful names, making stylesheets easier to understand and maintain. Using variables makes your code more readable and makes the intent of the style clearer than hardcoding values ​​or colors.

  • global control

    CSSGlobal style control can be achieved by defining variables on the root element . This means you can use the same variables throughout your website, ensuring a consistent look and feel. If you need to change a style, you only need to modify the value of the variable without modifying each specific style one by one.

Guess you like

Origin blog.csdn.net/Shids_/article/details/134502119