温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

CSS3怎么给文本添加背景图

发布时间:2021-08-25 09:49:30 来源:亿速云 阅读:90 作者:chen 栏目:web开发

本篇内容主要讲解“CSS3怎么给文本添加背景图”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“CSS3怎么给文本添加背景图”吧!

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

我们先来看看效果图:

CSS3怎么给文本添加背景图

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

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

<body>
  <h2>Hello world!</h2>
  <h4>Hello world!</h4>
</body>

CSS3怎么给文本添加背景图

然后开始定义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;
}

CSS3怎么给文本添加背景图

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

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

h2 {
	color: transparent;
	background-image: url("https://img.php.cn/upload/article/000/000/024/612360451cede816.jpg");
  
}
h4{
	color: transparent;
	background-image: url("https://img.php.cn/upload/article/000/000/024/6124c86e0808b298.jpg");
}

CSS3怎么给文本添加背景图

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

h2 {
	color: transparent;
	background-image: url("https://img.php.cn/upload/article/000/000/024/612360451cede816.jpg");
	background-clip: text;
	-webkit-background-clip: text;
  
}
h4{
	color: transparent;
	background-image: url("https://img.php.cn/upload/article/000/000/024/6124c86e0808b298.jpg");
	background-clip: text;
	-webkit-background-clip: text;
}

CSS3怎么给文本添加背景图

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

<!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;
			}

			h2 {
				color: transparent;
				background-image: url("https://img.php.cn/upload/article/000/000/024/612360451cede816.jpg");
				background-clip: text;
				-webkit-background-clip: text;

			}

			h4 {
				color: transparent;
				background-image: url("https://img.php.cn/upload/article/000/000/024/6124c86e0808b298.jpg");
				background-clip: text;
				-webkit-background-clip: text;
			}
		</style>
	</head>
	<body>
		<h2>Hello world!</h2>
		<h4>Hello world!</h4>
	</body>
</html>

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

h4 {
   background-image: url("https://img.php.cn/upload/image/161/146/599/1629799857734746.gif"),
   url("https://img.php.cn/upload/image/817/380/291/1629799861847258.gif");
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
}

CSS3怎么给文本添加背景图

到此,相信大家对“CSS3怎么给文本添加背景图”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI