我是靠谱客的博主 眼睛大向日葵,这篇文章主要介绍纯CSS3怎么给文本添加背景图,现在分享给大家,希望可以做个参考。

在之前的文章《手把手教你使用CSS3实现按钮悬停闪烁动态特效》中,我们介绍使用CSS3给按钮添加动态效果,实现一个按钮悬停闪亮阴影动画效果的方法,感兴趣的朋友可以去了解一下~

今天我们我们来看看使用CSS3怎么给文本添加背景图,让文字变得生动好看!在我们想要创建一个较大的文本标题,但不想使用普通又枯燥的颜色来修饰时,非常有用!

我们先来看看效果图:

1.png

下面我们来研究一下是怎么实现这个效果的:

首先是HTML部分,定义两个标题

复制代码
1
2
3
4
<body> <h1>Hello world!</h1> <h3>Hello world!</h3> </body>
登录后复制

2.png

然后开始定义css样式来进行修饰:

复制代码
1
2
3
4
5
6
7
8
9
10
11
body { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 100%; text-align: center; min-height: 100vh; font-size: 100px; font-family:Arial, Helvetica, sans-serif; }
登录后复制

3.png

最后就是给文字添加背景图片:

  • 将文字原本的颜色设置为transparent透明,然后利用background-image属性给文字加背景图片

复制代码
1
2
3
4
5
6
7
8
9
h1 { color: transparent; background-image: url("https://img.uoften.com/upload/article/000/000/024/612360451cede816.jpg"); } h3{ color: transparent; background-image: url("https://img.uoften.com/upload/article/000/000/024/6124c86e0808b298.jpg"); }
登录后复制

4.png

发现效果是这样的,不如人意。这是因为缺少了一个关键属性background-clip。background-clip属性是一个CSS3新属性,要添加前缀来兼容其他浏览器

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
h1 { color: transparent; background-image: url("https://img.uoften.com/upload/article/000/000/024/612360451cede816.jpg"); background-clip: text; -webkit-background-clip: text; } h3{ color: transparent; background-image: url("https://img.uoften.com/upload/article/000/000/024/6124c86e0808b298.jpg"); background-clip: text; -webkit-background-clip: text; }
登录后复制

5.png

ok,大功告成!下面附上完整代码:

复制代码
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
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> body { display: flex; align-items: center; justify-content: center; flex-direction: column; width: 100%; text-align: center; min-height: 100vh; font-size: 100px; font-family: Arial, Helvetica, sans-serif; } h1 { color: transparent; background-image: url("https://img.uoften.com/upload/article/000/000/024/612360451cede816.jpg"); background-clip: text; -webkit-background-clip: text; } h3 { color: transparent; background-image: url("https://img.uoften.com/upload/article/000/000/024/6124c86e0808b298.jpg"); background-clip: text; -webkit-background-clip: text; } </style> </head> <body> <h1>Hello world!</h1> <h3>Hello world!</h3> </body> </html>
登录后复制

因为我们使用的是静态图片,所以是文本背景图效果也是静态的。如果使用动图会有动态效果:

复制代码
1
2
3
4
5
6
7
h3 { background-image: url("https://img.uoften.com/upload/image/161/146/599/1629799857734746.gif"), url("https://img.uoften.com/upload/image/817/380/291/1629799861847258.gif"); background-clip: text; -webkit-background-clip: text; color: transparent; }
登录后复制

3.gif

靠谱客平台有非常多的视频教学资源,欢迎大家学习《css视频教程》!

以上就是纯CSS3怎么给文本添加背景图的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是眼睛大向日葵最近收集整理的关于纯CSS3怎么给文本添加背景图的全部内容,更多相关纯CSS3怎么给文本添加背景图内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部