使用图像填充文字的效果。具体来说,利用CSS的background-clip: text属性将一张图片作为文字的背景,并使文字本身透明,从而显示出图片中的内容。
代码说明
- HTML结构:
- 使用
<h1>标签来显示文本“网页特效库”。 - 添加了一个
.error-message的<div>元素,用于在浏览器不支持background-clip: text时显示错误信息。
- 使用
- CSS样式:
- 使用
@supports (background-clip: text)检查浏览器是否支持background-clip: text属性。 - 如果支持,则为
<h1>元素设置背景图像,并将其剪裁为文本形状,同时将文本颜色设为透明。 - 使用
calc(2rem + 12vw)动态调整字体大小,使其根据视口宽度变化。 - 使用
@layer reset-and-setup重置所有元素的box-sizing属性,并设置全局样式。 - 设置
body的高度为100%视口高度,并使用网格布局使其内容居中。 - 使用
@supports not (background-clip: text)检测浏览器是否不支持background-clip: text属性。 - 如果不支持,则显示
.error-message,提示用户升级浏览器。
- 使用
通过这种方式,我们创建了一个美观的图像填充文字效果,并确保在不支持该特性的浏览器中提供友好的错误提示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图像填充文字</title>
<style>
@supports (background-clip: text) {
h1 {
background-image:
url('https://syjm.net/public/demo2.webp');
background-clip: text;
color: transparent;
background-size: cover;
background-position: center;
font-size: calc(2rem + 12vw);
text-align: center;
}
}
@layer reset-and-setup {
* {
box-sizing: border-box;
color-scheme: light dark;
}
body {
margin: 0;
height: 100vh;
display: grid;
place-content: center;
}
}
.error-message { display: none; }
@supports not (background-clip: text) {
.error-message {
color: white;
padding: 2rem;
background: darkred;
display: block;
width: 100%;
text-align: center;
font-size: 1.3rem;
font-family: ui-system, sans-serif;
a {
color: #f1f170;
}
position: fixed;
top: 0;
}
}
</style>
</head>
<body>
<h1>网页特效库</h1>
</body>
</html>

One response
学了一招,原来文字还可以用图像填充