Css Property 使用

801 阅读2分钟

Css Property

参考列表

目录

Css Customer properties

Property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.

Property 命令是有--前缀的,例如--example-name, 代表一个可以被其它用var()方法声明了的地方使用的包含属性的自定义属性

Custom properties are scoped to the element(s) they are declared on, and participate in the cascade: the value of such a custom property is that from the declaration decided by the cascading algorithm.

自定义属性的作用域是声明了(属性的)组件,并参与级联:此类定制属性的值是级联算法确定的声明中的值。

Syntax

HTML
<p id="firstParagraph">This paragraph should have a blue background and yellow text.</p>
<p id="secondParagraph">This paragraph should have a yellow background and blue text.</p>
<div id="container">
  <p id="thirdParagraph">This paragraph should have a green background and yellow text.</p>
</div>
:root {
  --first-color: #16f;
  --second-color: #ff7;
}

#firstParagraph {
  background-color: var(--first-color);
  color: var(--second-color);
}

#secondParagraph {
  background-color: var(--second-color);
  color: var(--first-color);
}

#container {
  --first-color: #290;
}

#thirdParagraph {
  background-color: var(--first-color);
  color: var(--second-color);
}
主题切换功能:

通过切换body的className 来达到切换皮肤的效果

:root {
	--bgc: #fff;
	--color: #999;
}
.dark {
	--bgc: #999;
	--color: #fff;
}
.body{
	background-color: var(--bgc);
}
dib{
	color: var(--color);
}
<body>
	<div>color</div>
</body>

Css @property 可以理解为Css Customer properties的升级版,它有两种声明方法:

** Css @property的浏览器兼容性目前不算太好,所以使用前需要考虑清楚,可以作为渐进增强使用**

  • css @property 声明
@property --my-color {
  syntax: '<color>';
  inherits: false;
  initial-value: #c0ffee;
}
  • Javascript Css.registerProperty;
window.CSS.registerProperty({
  name: '--my-color',
  syntax: '<color>',
  inherits: false,
  initialValue: '#c0ffee',
});

使用 @property 可以实现一些普通情况下做不到的效果, 抄掘金 CSS @property,让不可能变可能

@property --houdini-colorA {
  syntax: '<color>';
  inherits: false;
  initial-value: #fff;
}
@property --houdini-colorB {
  syntax: '<color>';
  inherits: false;
  initial-value: #000;
}
.property {
	width: 200px; height: 200px;
    background: linear-gradient(45deg, var(--houdini-colorA), var(--houdini-colorB));
    transition: 1s --houdini-colorA, 1s --houdini-colorB;
    
}
.property:hover {
        --houdini-colorA: yellowgreen;
        --houdini-colorB: deeppink;
    }
	<div class="property"></div>