案例来源
本例来自CodingStartup的视频:[CSS] 聚光灯效果
学到知识
关于after伪元素中content内容的设置,除了直接写在后面,也可以将其值写在html自定义的属性值中,利用attr()函数通过属性名,获取属性值。
after伪元素的所在位置相当于是所使用的元素的子元素,所以可以使用父元素相对定位,伪元素绝对定位的方法,调整伪元素的位置。
使用clip-path来实现遮罩效果,本例中属性值为ellipse(100px 100px at 0% 50%),前两个参数为椭圆的x轴长度和y轴高度,at后的两个参数为相对于自身元素的x轴位置和y轴位置。
- 注意:使用这个属性时,需要注意浏览器的兼容情况,例如:Safari需要加前缀
-webkit-
- 在使用兼容前缀的时候,一定要保留原css(非前缀)代码,不可删去。
设置对文字设置背景时,默认是文字所在的块级元素覆盖背景,如果想要将背景仅作用于文字上,类似color的效果,可以使用背景遮罩
background-clip: text;
想要实现以上效果,背景仅覆盖文字区域,还需要将文字的color设置成transparent,表示全透明色彩。
网站分享:caniuse查看css属性在各种浏览器中的支持情况,以及需要使用的前缀。
主要代码
html
1 2 3
| <body> <h1 dot-light="Macbook Pro">Macbook Pro</h1> </body>
|
css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| body { margin: 0; display: flex; justify-content: center; align-items: center; background-color: #222; min-height: 100vh; }
h1 { font-size: 9rem; font-family: Helvetica; letter-spacing: -.3rem; color: #333; position: relative; }
h1::after { content: attr(dot-light); position: absolute; top: 0; left: 0; color: transparent; clip-path: ellipse(100px 100px at 0% 50%); animation: SpotLight 5s infinite; background-image: url("https://images.unsplash.com/photo-1568279898331-4870e84677dd?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTh8fGxpbmVhcnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60"); background-size: 150%; background-position: center center; -webkit-background-clip: text; background-clip: text; }
@keyframes SpotLight { 0% { clip-path: ellipse(100px 100px at 0% 50%); }
50% { clip-path: ellipse(100px 100px at 100% 50%); }
100% { clip-path: ellipse(100px 100px at 0% 50%); } }
|