CSS custom properties and theme switching of front-end pages

CSS custom properties based on cascading variables have been around for many years.
Although preprocessors such as less and sass are popular, custom attributes also have their characteristics and uses, such as reading and writing in js, scope setting, etc., and also play a great role in handling UI theme switching and other functions .

custom attributes

CSS custom properties (Custom Properties), which are defined inside a css selector, are named with two short horizontal connecting lines as the  -- beginning, which are called custom properties.
You can set any css attribute value for this custom attribute.
After the custom attribute is assigned, it can be assigned as a variable to the css style attribute, and it will take effect immediately.

Definition: --custom-property-name: custom-property-value.

Example:

body {
  /* 声明自定义属性 */
  --bg-color: #f00;
  /* 使用 */
  background-color: var(--bg-color);
}

The above code defines a  --bg-color custom attribute named under the body, and sets the value as a color value of red  #f00.
After being referenced by the background color of the body  background-color , the entire page will be rendered with a red background.

When using custom attributes to assign values ​​to css styles, you need to use the var() function, see below.

Naming rules

The naming rules of custom attributes are as follows:

  • Combinations of numbers [0-9], letters [a-zA-Z], underscores [_] and dashes [-] can be used
  • Text characters such as Chinese can be used
  • cannot use  $、[、^、(、% characters such as
  • Case Sensitive
div {
  --1: #0f0;
  --背景: yellow;
  --Fontsize: 20px;
  color: var(--1);
  font-size: var(--Fontsize, 30px);
  background-color: var(--背景);
}

As above, it can take effect if it is defined by means of numbers or Chinese.

value

When declaring a custom attribute, you need to assign a value to the attribute, and you can use any format supported by the CSS style attribute value.
Such as  #000, 12px, center, strings, numbers, etc.

{
  --1: #0f0;
  --2: center;
  --f: '测试';
  --n: 22;
  --z: 12px;
}

scope

The css custom attribute has a scope, that is, the css selector where it is declared.

  • When a custom attribute attribute is declared in a css selector, the element of the selector and all its child elements can use the custom attribute.
  • When declared :root below , it can be used throughout the document.

:root is a pseudo-class selector that matches the root element of the document. In  HTML , the root element is  <html> the element, but :root has higher priority, and the others are the same.

:root {
  --color: red;
}
body {
  --bg-color: #ddd;
  color: --color;
  background-color: var(--bg-color);
  width: var(--width); /*自定义属性变量无效*/
}
body .header {
  --width: 1000px;
  color: var(--color);
  background-color: var(--bg-color);
  width: var(--width);
}

The sample code above, the global variable declared in :root, can be used anywhere, while the one in body can be referenced by body and .header, and the one declared in .header cannot be referenced by body.

To use custom attributes, you must use the var() function. We will learn about the var() function below.

var() function

The var() function returns the value corresponding to the referenced custom property and is applied to the corresponding CSS property.
The var() function can only be used as the value of the attribute, and can replace any part of the value in the style attribute.
The var() function cannot be used as a property name, selector, or value other than a property value, and doing so would simply produce invalid syntax or invalid values.

Definition: var(custom-property-name, value).

  • custom-property-name Required, the name of the custom property.
  • value is optional, default fallback value.
div {
  --1: #0f0;
  --border-color: yellow;
  color: var(--1);
  border: 1px solid var(--border-color);
}

--border-color The color part is referenced as the border attribute.

default parameter

The second optional parameter of the var() function indicates the default fallback value; if the custom attribute does not exist, the default parameter value will be used as the attribute value.

div {
  font-size: var(--Fontsize, 30px);
}

As in the above code, when  --Fontsize it does not exist,  font-size the value of the attribute is  30px.

Note: the default fallback value will only be used if our custom property is not defined .
If the value of the custom attribute is an error value or is not legal, the default value will not be used, but the default value of the style attribute will be used instead.
If the default value is also an incorrect value, the property's default value is used.

<div style="--text-color: 11px;">
  <span style="color: var(--text-color, #f00);">欢迎进入我们的网站</span>
  <span style="color: var(--1color, #f00);">今天是星期天</span>
  <span style="color: var(--1color, 22px);">晴到多云</span>
</div>

As shown in the above code, the default value of the color attribute is black  #000, in a few paragraphs of text:

  • "Welcome to our website" because  --text-color the value of is not a color value, so the default value does not work and displays black;
  • "Sunny to cloudy"  --1color does not exist, and the default value  22px is not a color value, so the default value black is also displayed;
  • "Today is Sunday" is displayed in red because  --1color it does not exist, and the default value  #f00 red is valid.

Usage of different values

When using the var() function variable, there are several special situations that need attention.

Values ​​to use for custom attributes

The var() function variable can also be applied to custom attribute declarations, and is referenced as a value, in the same way.

div {
  --1: #0f0;
  --背景: var(--1);
  color: var(--1);
  border: 1px solid var(--背景);
}

--背景 Attributes use  -1 attributes for assignment.

for string combination

When the value of the custom attribute is a string, it can be directly concatenated with the string of the style attribute value, which is mostly used for the content attribute, as follows:

:root {
  --wait-copy: ',请复制';
}
div:after {
  content: '正文'var(--wait-copy);
}

contentThis will display the concatenated : text, please copy on the page  .

For calc() digital calculations

When the value of the custom attribute is a number, in addition to  the css attributes that can be used for opacity, etc. that use numbers, you can also use the calc function for calculation processing. As follows:z-index

:root {
  --size: 5;
  --width: calc(100px * 5);
}
.div {
  width: var(--width);
  font-size: calc(var(--size) * 10px);
}

Style properties can be changed through calc calculations.

Use in inline styles

Custom attributes are the same as general css attributes, and we can also use these attributes in the inline style of elements.
As follows:

<div style="--text-color: red;">
  <span style="color: var(--text-color);">欢迎进入我们的网站</span>
  <span class="week">今天是星期天</span>
</div>
.week {
  color: var(--text-color);
}

A color attribute is declared in  div the inline style of the element  --text-color, and in the sub-element of div, it can be referenced and effective through inline style and class style.

used in SVG

The use of svg in html can be used in the form of pictures like jpg, png, etc., or directly in the form of labels.
When we use svg in the form of tags on the page, we can directly refer to the custom variable attributes, which are used in the same way as in html, as follows:

:root {
  --color: red;
}
body {
  --color: green;
  --bg-color: #ddd;
  background-color: var(--bg-color);
}
<svg width="32" height="32" xmlns="http://www.w3.org/2000/svg">
  <g fill="none" fill-rule="evenodd">
    <circle stroke="var(--color)" cx="16" cy="16" r="12"/>
    <path d="M16.5 21.5c.672 0 1.5-.084 1.5-.5V11a1 1 0 0 0-1-1h-3.5a.5.5 0 0 0-.5.5v1.112c0 .223.18.404.404.404.135 0 .667.161 1.596.484V21c0 .416.828.5 1.5.5Z" fill="var(--color)" fill-rule="nonzero"/>
  </g>
</svg>

However, the svg icon referenced in the form of an image cannot use custom attributes. If you really want to modify the color of the svg icon, you can use drop-shadow.

drop-shadow modify svg icon color

Add style to the icon (use the shadow area of ​​the original icon for processing):

  • Add the transform attribute to the icon element of the svg icon, move it out of the visual area and hide it
  • Add the filter attribute to the icon element, and use the drop-shadow shadow value to handle it. The shadow displacement should be the same as the translateX movement distance
  • Add the overflow attribute to the parent element, hide the content beyond the range, hide the original moving icon, and display the shadow area
/*父元素*/
.parent {
  overflow:hidden;
}

/*svg图标*/
img.icon {
  transform: translateX(-80px);
  filter: drop-shadow(red 80px 0);
}

This method is more suitable for svg icons that do not require event operations.

read and write in javascript

Custom attribute variables can be read and written through javascript, and can be easily operated.  The methods 
of the style object are mainly used here   .setProperty()getPropertyValue()

  • Manipulate global attributes
:root {
  --color: red;
}
const root = getComputedStyle(document.documentElement)
// 获取全局属性值
const color1 = root.getPropertyValue('--color').trim()
// 设置属性值
document.documentElement.style.setProperty('--color', 'green')
const color2 = root.getPropertyValue('--color').trim()

console.log(color1, color2) // red green

// 给元素设置样式
const body = document.querySelector('body')
document.querySelector('body').style.backgroundColor = color2
// body的背景色将被设置为绿色
  • Read and write element attributes
<div id="welc" style="-text-pos: center;">
</div>
// 获取welc元素下定义的属性值,给body设置该值
const welc = document.getElementById('welc')
const align = welc.style.getPropertyValue('--text-pos')
// welc.style.setProperty('--text-pos', 'left')
document.querySelector('body').style.textAlign = align

Use: root theme switch

When we use the :root selector to define global attributes, we can switch the theme through this selector.
Here, we also need to introduce  theme, combined: root selector and js can be better handled, as follows:

  • Define the global properties of different themes, as follows, the black and white themes are defined:
:root[theme="black"] {
  --color: #000;
}
:root[theme="white"] {
  --color: #fff;
}
  • To use these custom attribute variables in web pages, skip
  • You can switch the theme by changing the value of theme through js, as follows:
const setDocumentTheme = (theme = 'white') => {
  const docElm = document.documentElement
  if (!docElm.hasAttribute('theme')) {
    docElm.setAttribute('theme', theme)
  } else {
    docElm.removeAttribute('theme')
  }
}

By calling the above js function, you can switch the theme and change the UI style of the web page.

compatibility

Most major browsers can be used, of course, except IE.

You can also use js for detection, which is supported under ie:

// 是否支持自定义属性
window.CSS && window.CSS.supports && window.CSS.supports('--a', 0)

You can also use css  @supports to judge, but ie does not support this css feature, so it is almost useless:

@supports ((--a: 0)) {
  /* 支持 */
}
@supports (not (--a: 0)) {
  /* 不支持 */
}

Guess you like

Origin blog.csdn.net/jh035/article/details/128128126