likes
comments
collection
share

CSS图像填充文字(镂空文字效果 / 文字镂空效果)

作者站长头像
站长
· 阅读数 64

先展示一下最终效果:

CSS图像填充文字(镂空文字效果 / 文字镂空效果)

开始做

1. 搭建基本代码结构

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CSS图像填充文字(镂空文字效果)</title>
    </head>
    <body>
        <div class="text">CSS图像填充文字</div>
    </body>
</html>

2. 设置样式,给文字所在的盒子设置背景图片

  • 我所用到的背景图: CSS图像填充文字(镂空文字效果 / 文字镂空效果)
  • 该步骤代码展示:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>CSS图像填充文字</title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
    
                .text {
                    width: 100vw;
                    height: 100vh;
                    background: url('Images/1000666.jpg') no-repeat center;
                    background-size: contain;
                    color: #fff;
                    font-size: 100px;
                    font-weight: 700;
                    text-align: center;
                    line-height: 100vh;
                }
            </style>
        </head>
        <body>
            <div class="text">CSS图像填充文字</div>
        </body>
    </html>
    
  • 效果展示: CSS图像填充文字(镂空文字效果 / 文字镂空效果)

3. 添加文字裁剪属性 + 设置文字颜色为透明色

-webkit-background-clip: text;
该属性的意思:以 盒子内 文字 作为 裁剪区域 ,向外 裁剪,文字之外 的 区域 都将 被 裁剪掉
  • 注意:
    • vsCode 编辑器中,只写这么一个属性会有警告;
    • 效果也是能够正常显示的;
    • 想要去掉这个警告,只需添加一行代码即可实现:
      background-clip: text;
      
  • 该步骤代码展示:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>CSS图像填充文字</title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
    
                .text {
                    width: 100vw;
                    height: 100vh;
                    background: url('Images/1000666.jpg') no-repeat center;
                    background-size: contain;
                    /* color: #fff; */
                    /* 将文字颜色设置为透明色 */
                    color: transparent;
                    font-size: 100px;
                    font-weight: 700;
                    text-align: center;
                    line-height: 100vh;
                    /* 文字裁剪属性 */
                    background-clip: text; /* 添加这个式为了 VsCode 给出警告 */
                    -webkit-background-clip: text; /* 主要属性 */
                }
            </style>
        </head>
        <body>
            <div class="text">CSS图像填充文字</div>
        </body>
    </html>
    
  • 效果展示: CSS图像填充文字(镂空文字效果 / 文字镂空效果)
  • 至此已经实现了文字镂空效果;
转载自:https://juejin.cn/post/7235167849429663801
评论
请登录