前端相较于后端等领域,能够在短时间内拥有可视化的成果,对于刚起步的小伙伴而言,这是不断努力学习提高的巨大动力,本篇博客抛砖引玉,利用HTML+CSS实现彩虹文字以及聚光灯动画效果,首先向大家介绍应用的CSS的主要属性
- background-clip
:
Thebackground-clip
CSS property sets whether an element's background extends underneath its border box, padding box, or content box. - clip-path
:
Theclip-path
CSS property creates a clipping region that sets what part of an element should be shown. Parts that are inside the region are shown, while those outside are hidden.
上述为background-clip属性和clip-path属性在MDN上的定义,总结来看,background-clip设置元素的背景是否扩展到其边框框、填充框或内容框之下,各个不同的属性值具体表现如下图所示,其中,本博客实现彩虹文字特效的方案利用background-clip:text实现,而clip-path属性则会创建一个剪切区域,用于设置元素应该显示的部分。区域内的部分显示出来,而区域外的部分则隐藏起来。
有了上述两个属性,我们可以轻松实现类似下面视频中的聚光灯效果,核心思路为,利用绝对定位不占位置的特点,重叠的设置两个盒子,并在将上层盒子的内容设置为彩虹文字,并且上层盒子的内容利用clip-path属性部分显示,具体源码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>聚光灯</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #222;
}
h1 {
position: relative;
color: #333333;
font-size: 8rem;
}
h1::after {
position: absolute;
left: 0;
top: 0;
content: "聚光灯";
background: -webkit-linear-gradient(left, #c23636, #192a56, #00d2d3, yellow, #6d2a4f, #2e86de, #4cd137, #e84118);
-webkit-background-clip: text;
color: transparent;
-webkit-clip-path: circle(100px at 0% 50%);
animation: light linear 4s infinite alternate;
}
@keyframes light {
0% {
-webkit-clip-path: circle(100px at 0% 50%);
}
50% {
-webkit-clip-path: circle(100px at 50% 50%);
}
100% {
-webkit-clip-path: circle(100px at 100% 50%);
}
}
</style>
</head>
<body>
<h1>聚光灯</h1>
</body>
</html>
本系列博客会陆续更新,主要内容为所前端学习过程中的心得体会,如感兴趣,大家多关注鼓励