[CSS] 聚光灯效果[练习]

案例来源

本例来自CodingStartup的视频:[CSS] 聚光灯效果

学到知识

  1. 关于after伪元素中content内容的设置,除了直接写在后面,也可以将其值写在html自定义的属性值中,利用attr()函数通过属性名,获取属性值。
  2. after伪元素的所在位置相当于是所使用的元素的子元素,所以可以使用父元素相对定位,伪元素绝对定位的方法,调整伪元素的位置。
  3. 使用clip-path来实现遮罩效果,本例中属性值为ellipse(100px 100px at 0% 50%),前两个参数为椭圆的x轴长度和y轴高度,at后的两个参数为相对于自身元素的x轴位置和y轴位置。
    • 注意:使用这个属性时,需要注意浏览器的兼容情况,例如:Safari需要加前缀-webkit-
    • 在使用兼容前缀的时候,一定要保留原css(非前缀)代码,不可删去。
  4. 设置对文字设置背景时,默认是文字所在的块级元素覆盖背景,如果想要将背景仅作用于文字上,类似color的效果,可以使用背景遮罩background-clip: text;
    • 同样要注意兼容问题。
  5. 想要实现以上效果,背景仅覆盖文字区域,还需要将文字的color设置成transparent,表示全透明色彩。
  6. 网站分享:caniuse查看css属性在各种浏览器中的支持情况,以及需要使用的前缀。

主要代码

html


    

Macbook Pro

css

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%);
    }
}

你可能感兴趣的:([CSS] 聚光灯效果[练习])