渐层色的转场与动画
在正常的情况下,CSS 无法制作“渐层色转场”或“渐层色动画”,但只要运用 CSS 的自订属性“@property”就能做出渐层色的转场与动画效果,这篇教学会介绍相关做法。
快速导览:
渐层色的转场 ( transition )
下方范例先透过 @property 建立 --c1 和 --c2 两个“颜色”属性值,接着设定在转场 transition 中指定这两个属性值的转场时间 ( 自订属性值需要额外设定 ),以及在渐层色中使用这两个自订属性,最后当 hover 悬停事件发生时修改属性值,就能实现渐层色的转场。
<!-- HTML 程式碼 -->
<h1>oxxo</h1>
<!-- CSS 程式碼 -->
<style>
/* 設定第一組顏色 */
@property --c1 {
syntax: "<color>";
inherits: true;
initial-value: red;
}
/* 設定第二組顏色 */
@property --c2 {
syntax: "<color>";
inherits: true;
initial-value: yellow;
}
h1 {
margin: 10px;
width: 200px;
height: 200px;
border: 1px solid #000;
color: red;
text-align: center;
font-size: 60px;
line-height: 200px;
transition: all 1s, --c1 1s, --c2 1s; /* 分別指定轉場時間 */
background: linear-gradient(var(--c1), var(--c2)); /* 設定漸層色 */
}
h1:hover{
color: blue;
--c1: cyan; /* 改變屬性值 */
--c2: green; /* 改變屬性值 */
}
</style>
自订属性不单纯只能设定颜色,下方范例改成“角度”和“百分比”的自订属性,就能运用渐层色,做出许多特别的转场效果。
<!-- HTML 程式碼 -->
<h1>oxxo</h1>
<!-- CSS 程式碼 -->
<style>
/* 角度自訂屬性 */
@property --angle {
syntax: "<angle>";
inherits: true;
initial-value: 180deg;
}
/* 百分比自訂屬性 */
@property --p1 {
syntax: "<percentage>";
inherits: true;
initial-value: 33%;
}
/* 百分比自訂屬性 */
@property --p2 {
syntax: "<percentage>";
inherits: true;
initial-value: 66%;
}
h1 {
margin: 10px;
width: 200px;
height: 200px;
border: 1px solid #000;
color: #fff;
text-align: center;
font-size: 60px;
line-height: 190px;
transition: all 1s, --angle 1s, --p1 1s, --p2 1s; /* 分別指定轉場時間 */
background: linear-gradient(var(--angle),
#fff 0%,
#fff var(--p1),
#09c var(--p1),
#09c var(--p2),
#069 var(--p2),
#069 100%); /* 設定漸層色 */
}
h1:hover{
color: #000;
--angle: 135deg; /* 改變屬性值 */
--p1: 80%; /* 改變屬性值 */
--p2: 90%; /* 改變屬性值 */
}
</style>
渐层色的动画 ( animation )
下方范例先透过 @property 建立 --p1、--p2 和 --p3 三个“长度”属性值,接着设定在定义动画的 @keyframes 中修改自订属性,就能实现渐层色的动画效果。
<!-- HTML 程式碼 -->
<h1></h1>
<!-- CSS 程式碼 -->
<style>
/* 定義第一個位置屬性 */
@property --p1 {
syntax: "<length>";
inherits: true;
initial-value: 0px;
}
/* 定義第二個位置屬性 */
@property --p2 {
syntax: "<length>";
inherits: true;
initial-value: 20px;
}
/* 定義第三個位置屬性 */
@property --p3 {
syntax: "<length>";
inherits: true;
initial-value: 40px;
}
h1 {
width: 200px;
height: 200px;
border: 1px solid #000;
background-image: repeating-linear-gradient(
45deg,
orange var(--p1), orange var(--p2),
black var(--p2), black var(--p3)); /* 設定漸層色 */
animation: 1s linear infinite oxxo; /* 設定動畫 */
}
@keyframes oxxo {
0% {
--p1: 0px; /* 改變屬性值 */
--p2: 20px; /* 改變屬性值 */
--p3: 40px; /* 改變屬性值 */
}
100% {
--p1: 40px; /* 改變屬性值 */
--p2: 60px; /* 改變屬性值 */
--p3: 80px; /* 改變屬性值 */
}
}
</style>
小结
透过 @property 自订属性,可以让原本无法进行转场或动画效果的“渐层”变得有趣,也可以让原本不容易处理的效果变得方便,有机会不妨在自己的网站中使用看看。
微信扫码关注
抖音扫码关注