最新消息: 关于Git&GitHub 版本控制你了解多少?
您现在的位置是:群英 > 开发技术 > web开发 >
css怎样对文本添加背景图片?
PHP中文网发表于 2021-08-28 17:37 次浏览

    css怎样对文本添加背景图片?一些朋友在设计网站页面的时候,想要让文字段落更好看,就可以给文件添加图片,这样就让文本段落更丰富了。对此,这篇文章就给大家分享一下怎样用纯css给文本添加背景,效果图如下,接下来我们具体了解看看吧。

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

<body>
  <h1>Hello world!</h1>
  <h3>Hello world!</h3>
</body>

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

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

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

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

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

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

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

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

			}

			h3 {
				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>
		<h1>Hello world!</h1>
		<h3>Hello world!</h3>
	</body>
</html>

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

h3 {
   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;
}

    以上就是关于css给文本添加背景代码了,有需要的朋友可以参考,希望对大家学习css有帮助,想要了解更多请关注群英网络其它相关文章。

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